Statics and Laravel 4?

So the other day I was thinking why I have to have to call every method as static in core Laravel modules! Where was the ugly PHP arrow operator (->)? I looked into the code and it led to some great ideas and unveiled some very neat practices.

Since I was then working with Views, it would only be relevant to take its make () method as an example. We call this method like this:

Now, that is nice way to call a view, but it actually is a non-static method lying in vendor/laravel/framework/src/illuminate/View/Environment.php. Here is how it happens:

First you have to look at app/config/app.php. There is an array of aliases. One of them would have the key: View and value: Illuminate\Support\Facades\View. In simplest terms this means that the Views modules can be called as View throughout the application and the vendor/laravel/framework/src/Illuminate/Support/Facades/View.php is acting as a Facade to the actual module files in vendor/laravel/framework/src/illuminate/View/ and is responsible for routing all requests from the application to the modules files. And the façade class is the one that is actually available through the excellent Laravel IOC container.

So when we call View::make (); it tries to call the make() methods from the Façade, which in reality does not exists there. But this is where the trick lies. When we open the Illuminate/Support/Facades/View.php file we will see that the class View extends from Facade class which does have a __classStatic(). According to PHP documentation:

So, the make () method is not found and since it is being called statically, the __callStatic() method gets triggered. Since this method takes two parameters, the inaccessible method name and its parameters, it gets the following parameters: First parameter : view name and second parameter as the view data. Now __callStatic looks for make () method in the namespace and finds one in vendor/laravel/framework/src/illuminate/View/Environment.php and calls the methods while passing it the parameters.

So, we come up with the following conclusion:

  • Great use of method overloading
  • Thank you Laravel team for getting rid of -> (at least for now)
  • Using Facades simplifies calls since we only have to remember the name of the facade class and even that name can be aliased.

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey
Share

Application developer, movie buff, occasional reader and a huge Manchester United fan.