The Facade pattern is a software design pattern which is often used in object oriented programming. A facade is, in fact, a class wrapping a complex library to provide a simpler and more readable interface to it. The Facade pattern can also be used to provide a unified and well-designed API to a group of complex and poorly designed APIs.
The Laravel framework has a feature similar to this pattern, also termed Facades. In this tutorial we will learn how to bring Laravel’s “Facades” to other frameworks. Before we continue, you need to have a basic understanding of Ioc containers.
Let’s first go through the inner working parts of Laravel’s facades, and then we’ll discuss how we can adapt this feature to the other environments.
Tóm Tắt
Facades in Laravel
A Laravel facade is a class which provides a static-like interface to services inside the container. These facades, according to the documentation, serve as a proxy for accessing the underlying implementation of the container’s services.
There have been many debates in the PHP community about this naming, though. Some have argued that the term should be changed in order to avoid confusion of developers, as it doesn’t fully implement the Facade pattern. If this naming confuses you, feel free to call it whatever feels right to you, but please note that the base class that we’re going to use is called Facade in the Laravel framework.
How Facades Are implemented in Laravel
As you probably know, every service inside the container has a unique name. In a Laravel application, to access a service directly from the container, we can use the App::make()
method or the app()
helper function.
<?php
App
::
make
(
'some_service'
)
->
methodName
(
)
;
As mentioned earlier, Laravel uses facade classes to make services available to the developer in a more readable way. By using a facade class, we would only need to write the following code to do the same thing:
someService
::
methodName
(
)
;
In Laravel, all services have a facade class. These facade classes extend the base Facade class which is part of the Illuminate/Support
package. The only thing that they need to implement is the getFacadeAccessor
method, which returns the service name inside the container.
In the above syntax, someService
refers to the facade class. The methodName
is in fact a method of the original service in the container. If we look at this syntax outside of the context of Laravel, it would mean that there’s a class named someService
exposing a static method named methodName()
, but that’s not how Laravel implements this interface. In the next section, we’ll see how Laravel’s base Facade class works behind the scenes.
Base Facade
The Facade class has a private property named $app
which stores a reference to the service container. If we need to use facades outside of Laravel, we have to explicitly set the container using setFacadeApplication()
method. We’ll get to that shortly.
Inside the base facade class, the __callStatic
magic method has been implemented to handle calling of static methods which don’t actually exist. When we call a static method against a Laravel facade class, the __callStatic
method is invoked, because the facade class hasn’t implemented that method. Consequently, __callStatic
fetches the respective service from the container and calls the method against it.
Here is the implementation of the __callStatic
method in the base facade class:
<?php
public
static
function
__callStatic
(
$method
,
$args
)
{
$instance
=
static
::
getFacadeRoot
(
)
;
switch
(
count
(
$args
)
)
{
case
0
:
return
$instance
->
$method
(
)
;
case
1
:
return
$instance
->
$method
(
$args
[
0
]
)
;
case
2
:
return
$instance
->
$method
(
$args
[
0
]
,
$args
[
1
]
)
;
case
3
:
return
$instance
->
$method
(
$args
[
0
]
,
$args
[
1
]
,
$args
[
2
]
)
;
case
4
:
return
$instance
->
$method
(
$args
[
0
]
,
$args
[
1
]
,
$args
[
2
]
,
$args
[
3
]
)
;
default
:
return
call_user_func_array
(
[
$instance
,
$method
]
,
$args
)
;
}
}
In the above method, getFacadeRoot()
gets the service from the container.
Anatomy of a Facade Class
Each facade class extends the base class. The only thing that we need to implement is the getFacadeAccessor()
method. This method does nothing but return the service’s name in the container.
<?php
namespace
App
\
Facades;
use
Illuminate
\
Support\
Facades\
Facade as
BaseFacade;
class
SomeServiceFacade
extends
BaseFacade
{
protected
static
function
getFacadeAccessor
(
)
{
return
'some.service'
;
}
}
Aliases
Since Laravel facades are PHP classes, we need to import them before we can use them. Thanks to the namespaces and autoloading support in PHP, all classes are automatically loaded when we access them by the fully-qualified name. PHP also supports aliasing of classes by using the use
directive:
use
App
\Facades\SomeServiceFacade
SomeServiceFacade
:
SomeMethod
();
However, we have to do this in each and every script where we need that particular facade class. Laravel handles the aliasing of facades in its own way by using an alias loader.
How Laravel Aliases the Facades
All alias names are kept in an aliases
array inside the app.php
config file, which is located inside the /config
directory.
If we take a look at the array, we can see that each alias name is mapped to a fully-qualified class name. This means we can use any name that we wish for a facade class:
// ..
'aliases'
=>
[
// ...
'FancyName'
=>
'App\Facades\SomeServiceFacade'
,
],
Okay, now let’s see how Laravel uses this array for aliasing the facade classes. In the bootstrapping phase, Laravel uses a service named AliasLoader
which is part of the Illuminate\Foundation
package. AliasLoader
takes the aliases
array, iterates over all the elements, and creates a queue of __autoload
functions using PHP’s spl_autoload_register. Each __autoload
function is responsible for creating an alias for the respective facade class by using PHP’s class_alias function.
As a result, we won’t have to import and alias the classes before using them as we normally do with the use
directive. So whenever we try to access a class that doesn’t exist, PHP will check the __autoload
queue to get the proper autoloader. By that time, AliasLoader
has already registered all the __autoload
functions. Each autoloader takes a fancy class name and resolves it to the original class name according to the aliases
array. Finally, it creates an alias for that class. Consider the following method call:
<?php
FancyName
::
someMethod
(
)
Behind the scenes, FancyName
is resolved to App\Facades\SomeServiceFacade
.
Using Facades in Other Frameworks
Okay, now that we have a good understanding of the way Laravel handles its facades and aliases, we can adapt Laravel’s facade approach to other environments. In this article, we’re going to use facades in the Silex framework. However, you can adapt this feature to other frameworks as well by following the same concept.
Silex has its own container, as it extends Pimple
. To access a service inside the container, we can use the $app
object like so:
<?php
$app
[
'some.service'
]
->
someMethod
(
)
With the help of facade classes, we can provide a static-like interface to our Silex services as well. In addition to that, we can use the AliasLoader
service to make meaningful aliases for those facades. As a result, we would be able to refactor the above code like so:
<?php
SomeService
::
someMethod
(
)
;
Requirements
To use the the base facade class, we need to install the Illuminate\Support
package using composer:
composer
require illuminate\
support
This package contains other services as well, but for now we just need its base Facade class.
Creating the Facades
To create a facade for a service, we just need to extend the base Facade class and implement the getFacadeAccessor
method.
For this tutorial, let’s keep all the facades under src/Facades
path. As an example, for a service named some.service
, the facade class would be as follows:
<?php
namespace
App
\
Facades
use
Illuminate
\
Support\
Facades\
Facade;
class
SomeServiceFacade
extends
Facade
{
protected
static
function
getFacadeAccessor
(
)
{
return
'some.service'
;
}
}
Please note that we have namespaced the class under app\facades
.
The only thing that remains is setting the application container on the facade class. As pointed out earlier, when we call a method in a static context against a facade class, __callStatic
is triggered. _callStatic
uses data returned by getFacadeAccessor()
to identify the service inside the container and tries to fetch it. When we’re using the base Facade class outside of Laravel, the container object isn’t set automatically, so we will need to do this manually.
To do this, the base facade class exposes a method named setFacadeApplication
which sets the application container for that facade class.
In our app.php
file, we need to add the following code:
<?php
Illumiante
\
Support\
Facade::
setFacadeApplication
(
$app
)
;
This will set the container for all the facades which are extending the base facade class.
Now, instead of accessing the service from our container, we can use the facade class we just created, also allowing us to call all methods in a static context.
Implementing the Aliases
To alias the facade classes, we’re going to use the AliasLoader
that we introduced earlier. Aliasloader
is part of the illuminate\foundation
package. We can either download the whole package or just borrow the code and keep it as a file.
If you just want to copy the source file, I suggest you keep it under src/Facades
. You can namespace the AliasLoader
class based on your project’s architecture.
For this example, let’s copy the code and namespace it under app/facades
.
Creating the Aliases Array
Let’s create a file in our config
directory called aliases.php
and put the alias-facade bindings in there like so:
<?php
return
[
'FancyName'
=>
'App\Facades\SomeService'
,
]
;
FancyName
is a name that we want to use instead of App\Facades\SomeService
.
Registering the Aliases
AliasLoader
is a singleton service. To create or get the alias loader’s instance, we need to call the getInstance
method with the array of aliases as an argument. Finally, to register all the aliases, we need to call its register
method.
Again in the app.php
file, add the following code:
<?php
$aliases
=
require
__DIR__
.
'/../../config/aliases.php'
;
App
\
Facades\
AliasLoader::
getInstance
(
$aliases
)
->
register
(
)
;
And that’s all there is to it! Now we can use the service like so:
<?php
FancyName
::
methodName
(
)
;
Wrapping Up
A Facade class only needs to implement the getFacadeAccessor
method which returns the service name inside the container. Since we’re using this feature outside of the Laravel environment, we have to explicitly set the service container using the setFacadeApplication()
method.
To refer to the facade classes, we either have to use the fully-qualified class names or import them with PHP’s use
directive. Alternatively, we can follow Laravel’s way of aliasing the facades by using an alias loader.
Questions? Comments? Leave them below! Thanks for reading!