Laravel 5: Facades

Facades


Facades provide a “static” interface to classes that are available in the application’s service container.

If you read above carefully, you will see that Laravel Facade is NOT a static way of calling methods.
It is a static accessor that builds a fully fledged and testable object for you.

So, instead of going via all this hurdles to build an object for yourself, Laravel Facade:

  • instantiating object for us
  • passes dependencies
  • and all works otherwise, you’d need to do yourself.

 

All available Facades are listed in: \config\app.php – then scroll down to: ‘aliases’

In order to use facades, you need too import facade accessor class, e.g.:

to use:

BTW:
Laravel facades are not static, untestable functions!
See accessor class for clues.


example 1:

When you do this using Facade:

… you actually sending Laravel a command to resolve object with keyword ‘form’ pointing to it and then call open method:

If you are puzzled about that: keywords mentioned above, see: here to find out more about Service Container binding.

 


example 2:

Let us see how it works on real life example – ‘Laravel Collective‘ – a component that used to be a part of Laravel, but it is not anymore and is maintained by community.

Laravel Collective has to be installed separately and once installed, it can be found here:

Once inside find this file and open it:

Inside you will find this code:

Now, we need to find this keyword. Best place to look is Service Provider.

Right in Laravel Collective directory, we can find this provider:

And inside of this file we have our keyword ‘form’:

As you can see above, our keyword bounds to this class:

… and if you look inside of this class, you will see all the methods you can chain to, e.g.:

And above frame can be used to build your own functionality and to define facades for them

 


What you find in example 2 applies to all other Facades, which can be found here:

… and in many other places in framework.
To find them all, just search for this phrase:

“protected static function getFacadeAccessor()”

 


Some more info

There are more ways to access data, besides facade, are mentioned here.
Also look at helper methods described on over 100 pages on this site.

PHP facade pattern vs. Laravel Facades in a nutshell:

  • Laravel Facade: clever way to simplify coders life (via auto-construction of objects behind scenes) without sacrificing testability etc.
    In a sense, this may have a bit to do with factory pattern, which also is primarily used to build object
  • PHP Facade Pattern: attaching switchboard-like class on top of other, worker classes, allowing to change/adjust worker classes without too much hassle to entire system – more info about facade patternread this.