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:
__callStatic() is triggered when invoking inaccessible methods in a static context.
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.
Latest posts by alexey (see all)
- Zend Soap NULL Reponse - August 29, 2018
- Quick Facts About WooCommerce - April 25, 2018
- WordPress stuck on a “Too many redirects” error loop when using SSL - January 17, 2018