Skip to content
Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 92 lines (61 sloc) 2.55 KB

Facades

In the Basic flow notes we saw how routes are declared using Laravel's Router Class:

Route::get('/', function () {
    # [...]
});

Before proceeding, let's take a moment to focus on the Route::get syntax because you'll see it used frequently throughout Laravel...

First, we need to address an aspect of object oriented programming which was not discussed earlier, and that's static methods.

When a method is declared as static, it is accessible without needing an instantiation of the class.

For example, imagine we had a class called Email with a method called send.

class Email {
    public function send() 
    {

    }
}

As written, in order to invoke send, we'd first have to instantiate a new email object:

$email = new Email();
$email->send();

However, if the send method was modified to indicate it was static...

class Email {
    public static function send() 
    {

    }
}

...we could then invoke the send method directly from the class using this double colon syntax:

Email::send();

Knowing this logistic of object oriented programming, it looks like Route::get is statically invoking a method called get from a class called Route.

This implies that the Route class is never instantiated, but that's not actually true. What we're seeing here is what Laravel calls a facade.

A facade is a “static alias” to a underlying class/object in Laravel.

Here's another example using Laravel's Hash facade:

$hashedPassword = Hash::make('secret123');

And another example using Laravel's App facade:

$currentEnvironment = App::environment();

Philosophy behind the use of facades

[Laravel facades] provide the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. -src

Facades and their classes

Here's a list of facades and their underlying classes.

Helpers

Some Laravel classes can also be accessed via a helper method which provides an even more terse syntax for commonly used methods.

For example, the Config class can be used like this:

$timezone = Config::get('app.timezone');

But there's also a helper method that can accomplish the same thing:

$timezone = config('app.timezone');

See a full list of available helper functions here...

You can’t perform that action at this time.