Learn How Laravel Facade Works By Building Your Own Facade

Learn How Laravel Facade Works By Building Your Own Facade

Hello there !! what's up ?

If you are Laravel developer or have worked in laravel already, I am pretty sure that you must have heard about Laravel Facade.Not only heard but you have implemented various methods in laravel using facade class.

Let's take one of the facade of laravel. On process of registration of any kind of form which contains password especially , we encrypt password data which come from form for security.For encryption,there is a method in laravel which is implemented this way:

<?php
use Illuminate\Support\Facades\Hash;
Hash::make($password);
// hashed out value of $password

You can see there that for using Hash::make() method we need to import facade class of Hash i.e use Illuminate\Support\Facades\Hash;.This is one of the example of Laravel facade. But actually what is facade and how it works ? if you go with laravel docs %[laravel.com/docs/8.x/facades#facade-class-r.. then you will find out that

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 general, it can be explained as a class which provides a static-like interface to services inside the service container.

Not much clear ? Don't worry.Let's dive into making our own facade class and understand how it works practically. well,we are going to replicate same facade class which i have taken as example above but this time we will implement on our own way.

so let's create HashServiceProvider.php using command php artisan make:provider HashServiceProvider which will create file inside App\Providers.Then register it inside App/config/app.php this way on array of providers,

'providers' => [
        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\HashServiceProvider::class,  // in this way 
    ],

After that let's create Support folder inside App directory and inside Support directory , create another folder called Facade which will contain two files viz. Facade.php and Hash.php .Similarly create another file HashManger.php but outside of Facade folder inside Support.This is how our directory looks like: Screenshot_20210628_004446.png Firstly, let's dive into HashManager.php file where we have implemented logic of hashing the given data. HashManager.php

Screenshot_20210628_005518.png As you can see it's just a php class where at first we have decleared protected $algo which generally refers to algorithm and inside __construct($algo) method we have assign to its parameter.Then we make public function make($value) which accept parameter as value and finally hashed the value which is as passed inside password_hash() method and returned hashed value .It was all about hashing the given data and second public function check($value,$hashed_value) which accepts two parameters,first one is $valuewhich is plain text and second $hashed_value which is hashed value of your $value and after passing those arguments of these parameters inside password_verify() method , it verify whether they matched or not and finally return boolean value based on true or false statement. Now, let's move towards HashServiceProvider.php and inside register() method bind our HashManager.php class which ultimately return new instance of the class.

Screenshot_20210628_145655.png This is how we bind our HashMananger class and we pass our argument as we have declared the $valueas parameter in __construct($value)method in HashManager.php and return it.One of the advantage of this binding is we don't need to make another new instance of class for accessing the properties and methods of class in any other place once we have bind it in service container and return it.If you are not getting what i m saying , no worries !! we are going to see it soon which makes you crystal clear.

Then let's dive into our Hash.php file which is inside App\App\Support\Facade and make protected static function getFacadeAccessor() inside it.

Screenshot_20210628_151618.png If you have notice then you see there that we have extends our parent class Facade.php which we will see after this.And inside static function getFacadeAccessor() we have resolve a class instance from the container by doing app(HashManager::class) & return it. So it generally means that we are returning the new instance of our HashManager class that we have make and returned after binding in HashServiceProvider.

Now let's move into the parent class Facade.php which we have extends in our Hash.php.This is how our Facade.php looks like:

Screenshot_20210628_175021.png As you see there , i have used a __callStatic() method. So basically in php it is a kind of static function which is being called in case if our called static function is not available in our class. Like for example:

<?php 
class Facade
{
    public static function __callStatic($method, $arguments)
    {
        return 'hello there';
    }
}
Facade::hello(); //// hello there

Here i do not have any hello() static function in our Facade class but even if we called it and if there is __callStatic($methods,$arguments) method then it will be called automatically. It has two parameters on which first one gives the name of our static function i.e hello and second one give the argument we have passed in our function.Hope you are clear about it.

Now let's see about this code return (static::getFacadeAccessor())->$method(...$arguments);

By doing this (static::getFacadeAccessor()) we are calling our getFacadeAccessor() static method from our child class Hash.php which ultimately returns instance of our HashManager class and after that we are dynamically getting $methods and calling it by passing $arguments from the function itself. So,this is the core idea behind the implementation of laravel facade We have finished building facade ,now time to use it and understand it more clearly.

So basically for its implementation I will be using web.php but you can use controller also.This is web.php

Screenshot_20210628_182412.png

You can see clearly that i have import and use my own Hash facade and by doing Hash::make('Gunaraj') we are calling static method make() from Hash class but wait, if you see in Hash.php there is no any static method callled make() but it eventually called the __callstatic($method,$arguments) method and there we are getting instance of HashManager class and calling $methods dynamically which will call make($value) method [in our case] from HashManager class and (...$arguments) is about passing arguments to our dynamic method. So in short it will call the non-static make() method behind the scene being called statically from web.php . Output: Screenshot_20210628_182209.png Yay !! we are done. We hashed it using our own laravel facade. Similarly,let's test another method,

<?php

use App\Support\Facade\Hash;   //Our Facade Class   

//use Illuminate\Support\Facades\Hash;  //This is Laravel Facade Class

use Illuminate\Support\Facades\Route;

//dd(Hash::make('Gunaraj'));
dump(Hash::check('Gunaraj','$2y$10$QAK7ZW9v2GSJ8alzQwO2xunfKJHZ2lyAo7wTEvhjqOUfpoEVX9pwW'));

It will dump true as you can can see below also because we check right hashed value.

Screenshot_20210628_190703.png

Finally, we successfully build our custom laravel facade and learn about it practically.Not the exact same way but in a similar way Laravel also makes its facade class. To get more insights about core laravel facades classes, u can go inside Illuminate\Support\Facades directory which falls under vendor\laravel\framework .

So let's sum up about laravel facade and give our own definition,it is actually a class which implements various methods of other classes ,made for specific task[like hasing in our case] being called non-statically behind the scene though called statically in front of scene.

But why need laravel facade ?Why to use it ?

  • We don’t have to remember long class names , which needs to be imported or injected before using them for its memorable syntax
  • Expressive,short and handy syntax
  • Easy to use and remember and many more...

With this i have ended up explaining all about laravel facade which i have target to do in this blog.Hope you understand something about laravel facade.Your feed backs are highly appreciated.

Have a nice day !!