Your First Custom Facade in Laravel

Laravel 3 mins read

Table of Content

    Introduction

    Facades in Laravel provides in general a static interface to a class that gives access to an object from the service container. In this article we will learn what's facades exactly, how to use them and how to create your own facade.

    What is Facades in Laravel?

    Referring to the laravel Docs

    Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

    In another word, instead of creating a static method to call them later from their own class, with facades you can create a normal method and call them statically without the need of making them as static methods.

    How Facades Works?

    Before knowing how it works, we should know that all of Laravel's facades are defined in the Illuminate\Support\Facades namespace. So, we can easily access a facade like so:

    use Illuminate\Support\Facades\Cache;
    
    Route::get('/cache', function () {
        return Cache::get('key');
    });
    

    You can define a facade simply by using getFacadeAccessor method for a facade class. Let's take a look at the Log Facade ships with laravel

    <?php
    
    namespace Illuminate\Support\Facades;
    
    class Log extends Facade
    {
        /**
         * Get the registered name of the component.
         *
         * @return string
         */
        protected static function getFacadeAccessor()
        {
            return 'log';
        }
    }
    

    So, The Log class extends the base abstracted facade Illuminate\Support\Facades\Facade and create the protected static facade accessor and all what that method does, it's just returns log keyword.

    The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container. In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static get method is being called on the Log class.

    The most powerfully things in facades is that after creating it and return the keyword in the facade accessor and Finlay bind in inside the Services Container -which we will learn later-, you can access them anywhere in your application. Cool, isn't it?

    Facades VS. Dependency Injection

    Before we dive into creating our custom facade, we must know the deference between the Facades and the Dependency Injection.

    Referring again to Laravel Docs:

    One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.

    Facades Vs. helper Functions

    If you played around with laravel a little, you sure notice there are a lot of helper functions such as view(), session() or cache().

    So, have you ever wonder between this helper functions and the facades since you can achieve the same result if you typed session()->put('key', 'coderflex') or Session::put('key', 'coderflex') ?

    The Answer to this question is quite simple in fact, the short answer to this is There is no difference between facades and helper function.

    The Detailed Answer is: Laravel includes a variety of "helper" functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:

    return Illuminate\Support\Facades\View::make('profile');
    
    return view('profile');
    

    Under the hood, the cache helper is going to call the get method on the class underlying the Cache facade. So, even though we are using the helper function.

    How to Create a custom facade

    We arrived to the most exciting part is that we will create our own custom facade, I'm so excited. Are you?

    To achieve this point there is some step we must follow:

    • Create a PHP class file.
    • Create new Service Provider for our facades.
    • Register That Service Provider in config/app.php.
    • Bind the created class to the Service Provider.
    • Register Our new facade in config/app.php under aliases.
    • Create The Facade class.
    • Register Your facade as an alias.

    Create a PHP class

    Let's Create a helper class under app folder to retrieve Site SEO information

    namespace App\Coderflex;
    
    class Coderflex
    {
        public function getSeoTitle()
        {
            echo "Full Guide to facades in laravel";
        }
    
        public function getSeoDescription()
        {
            echo "here you can what ever you want...";
        }
    }
    

    Notice that the get keyword in the begging is not reserved word or something like that, you can name your method whatever you like.

    Create new Service Provider.

    After creating our class we must bind it in the service provider.

    To create a new Service provider -it's not necessary but to organize your work- execute the following command inside your CMD/Terminal

    php artisan make:provider CoderflexServiceProvider
    

    The generated service provider lives in app/Providers/CoderflexServiceProvider, and inside it, you must add in the register method the following:

    public function register()
    {
        // ....
            $this->app->bind('coderflex', function () {
                return new Coderflex();
            });
        // ....
    }
    

    after typed those line of codes your service provider class should look like:

    namespace App\Providers;
    
    use App\Coderflex;
    
    use Illuminate\Support\ServiceProvider;
    
    class CoderflexServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            //
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
            $this->app->bind('coderflex',function(){
    
            return new Coderflex();
    
            });
        }
    }
    

    Register Service Provider

    After creating the service provider successfully You must register it in config/app.php in providers array

    // ...
    
    'providers' => [
    
        /* Custom Service Providers */
        App\Providers\CoderflexServiceProvider::class,
    ],
    // ...
    

    Create The Facade Class

    Create a facade class CoderflexFacade inside App\Coderflex which will extend Facade abstract class

    inside app/Coderflex/CoderflexFacade.php

    namespace App\Coderflex;
    
    use Illuminate\Support\Facades\Facade;
    
    class CoderflexFacade extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'coderflex';
        }
    }
    
    

    Register Your facade as an alias

    You can register your created class inside config/app.php as and alias, and it's unnecessary step by the way it's just for calling the facade as use Coderflex for example instead of the full namespace such use App\Coderflex\CoderflexFacade. It's you call :)

    // ...
    'aliases'   => [
        // ....
        'Coderflex' => App\Coderflex\CoderflexFacade::class,
    ],
    // ...
    
    

    Test Your Facade

    I would to say Congratulation 〽, you made it so far! Nothing left to add except testing your facade if it works, or it's waste of time 😁

    Inside your web file routes/web.php

    Route::get('/coderflex', function () {
       Coderflex::getSeoTitle();
    });
    
    

    And you should see after visiting your-domain.tld/coderflex the SEO title we wrote before.

    Conclusion

    Today we saw Laravel Facades and how it works. In the conclusion of all what we saw in this article, create a class under app directory, create the facade class with coderflex returned from the accessor method, bind the created class and the facade inside the service provider with (returned name from the getFacadeAccessor() method and the name of the class).

    That's it for today folks! Thanks for Reading and I hope to see you in another article.


    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    Our news letter sent once a week, every tuesday.