How Laravel Facades Work and How to Use Them Elsewhere

Reza Lavarian
Reza Lavarian
Share

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.

Facades diagram

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.

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
// ...
/**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     */
    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 {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    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 is resolved to App\Facades\SomeServiceFacade according to the aliases array

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 {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    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!

Frequently Asked Questions (FAQs) about Laravel Facades

What are the key differences between Laravel Facades and traditional PHP static methods?

Laravel Facades and traditional PHP static methods may seem similar, but they are fundamentally different. Traditional PHP static methods, once defined, cannot be changed or extended. They are fixed and rigid. On the other hand, Laravel Facades are more flexible and dynamic. They provide a static interface to classes that are available in the application’s service container. This means you can swap out the underlying class the Facade represents without changing your code. This is particularly useful for testing, where you can replace a Facade with a mock implementation.

How can I create a custom Facade in Laravel?

Creating a custom Facade in Laravel involves three steps. First, you need to create the class that the Facade will represent. This class should be bound to Laravel’s service container. Second, you need to create the Facade class itself. This class should extend the base Facade class provided by Laravel and implement the getFacadeAccessor method. This method should return the binding of the class in the service container. Finally, you need to register the Facade class with Laravel. This can be done in the config/app.php file.

Can I use Laravel Facades outside of Laravel?

Yes, you can use Laravel Facades outside of Laravel. This is possible because Facades are not tied to Laravel’s framework. They are simply a design pattern that Laravel uses extensively. To use Facades outside of Laravel, you need to set up a service container and bind your classes to it. Then, you can create Facade classes that provide a static interface to these classes.

What are the benefits of using Laravel Facades?

Laravel Facades offer several benefits. They provide a simple, expressive syntax that makes your code easier to read and understand. They also provide a static interface to classes in the service container, which makes it easy to swap out implementations without changing your code. This is particularly useful for testing. Furthermore, Facades are resolved out of the service container, which means they are automatically resolved and their dependencies are automatically injected.

Are there any drawbacks to using Laravel Facades?

While Laravel Facades offer many benefits, they also have a few drawbacks. One of the main criticisms of Facades is that they can make your code harder to test and debug. This is because Facades hide the underlying complexity of the code, which can make it difficult to understand what’s going on. Additionally, because Facades provide a static interface, they can lead to tightly coupled code if not used carefully.

How do Laravel Facades work under the hood?

Laravel Facades work by providing a static interface to classes in the service container. When you call a method on a Facade, Laravel will resolve the underlying class out of the service container and call the method on that class. This is done using PHP’s __callStatic magic method. The Facade class itself doesn’t contain any logic. It simply delegates the method call to the underlying class.

Can I use Laravel Facades with Laravel’s dependency injection?

Yes, you can use Laravel Facades with Laravel’s dependency injection. In fact, Facades are a form of dependency injection. When you use a Facade, Laravel will automatically resolve the underlying class out of the service container and inject any dependencies it needs. This makes it easy to manage your dependencies and keep your code decoupled.

How can I test code that uses Laravel Facades?

Laravel provides several tools for testing code that uses Facades. One of these tools is the Facade::shouldReceive method. This method allows you to set up expectations for Facade methods and return mock responses. This makes it easy to isolate your code and test it in isolation.

Can I use Laravel Facades in controllers?

Yes, you can use Laravel Facades in controllers. In fact, Laravel encourages the use of Facades in controllers. This is because controllers are typically responsible for handling HTTP requests and returning responses, which often involves interacting with various services in your application. Facades provide a simple, expressive syntax for interacting with these services.

How can I learn more about Laravel Facades?

There are many resources available for learning more about Laravel Facades. The official Laravel documentation is a great place to start. It provides a comprehensive overview of Facades and how to use them. There are also many tutorials, blog posts, and online courses available that cover Facades in more detail.