⌘K
Noting Found

View all related articles

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:

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

    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

    1<?php
    2 
    3namespace Illuminate\Support\Facades;
    4 
    5class Log extends Facade
    6{
    7 /**
    8 * Get the registered name of the component.
    9 *
    10 * @return string
    11 */
    12 protected static function getFacadeAccessor()
    13 {
    14 return 'log';
    15 }
    16}

    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:

    1return Illuminate\Support\Facades\View::make('profile');
    2 
    3return 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

    1namespace App\Coderflex;
    2 
    3class Coderflex
    4{
    5 public function getSeoTitle()
    6 {
    7 echo "Full Guide to facades in laravel";
    8 }
    9 
    10 public function getSeoDescription()
    11 {
    12 echo "here you can what ever you want...";
    13 }
    14}

    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

    1php 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:

    1public function register()
    2{
    3 // ....
    4 $this->app->bind('coderflex', function () {
    5 return new Coderflex();
    6 });
    7 // ....
    8}

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

    1namespace App\Providers;
    2 
    3use App\Coderflex;
    4 
    5use Illuminate\Support\ServiceProvider;
    6 
    7class CoderflexServiceProvider extends ServiceProvider
    8{
    9 /**
    10 * Bootstrap the application services.
    11 *
    12 * @return void
    13 */
    14 public function boot()
    15 {
    16 //
    17 }
    18 
    19 /**
    20 * Register the application services.
    21 *
    22 * @return void
    23 */
    24 public function register()
    25 {
    26 $this->app->bind('coderflex',function(){
    27 
    28 return new Coderflex();
    29 
    30 });
    31 }
    32}

    Register Service Provider

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

    1// ...
    2 
    3'providers' => [
    4 
    5 /* Custom Service Providers */
    6 App\Providers\CoderflexServiceProvider::class,
    7],
    8// ...

    Create The Facade Class

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

    inside app/Coderflex/CoderflexFacade.php

    1namespace App\Coderflex;
    2 
    3use Illuminate\Support\Facades\Facade;
    4 
    5class CoderflexFacade extends Facade
    6{
    7 protected static function getFacadeAccessor()
    8 {
    9 return 'coderflex';
    10 }
    11}

    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 :)

    1// ...
    2'aliases' => [
    3 // ....
    4 'Coderflex' => App\Coderflex\CoderflexFacade::class,
    5],
    6// ...

    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

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

    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 | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

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

    We care about the protection of your data. Read our Privacy Policy.