How Laravel Facade Works with Brief Example

Hello CodeCheef.org lover, in this example i will show you how Laravel facades work. In this Laravel facade example tutorial you will able to know that how Laravel facades work. In this example we will create our own custom facades class.

You know that Laravel facades gives us the static interface. That mean we can call a method statically without declaring it static. If you don't know about Laravel facades then this tutorial is going to be very helpful for you.

In this tutorial we will create our own facades that will work as like Laravel facades work. So let's see how we can create our own custom facades that doesn't extends facades class.

Example:

App\Helper.php

namespace App;

class Helper
{
    public function hello()
    {
        dd('abc');
    }
}

 

Look this is the helper class and hello() is not a static method. We will access it via our own custom facades. 

 

App\Facade.php

namespace App;

class Facade
{
   public static function resolveInstance($name)
   {
       return app()[$name];
   }

   public static function __callStatic($method, $arguments)
   {
        return (self::resolveInstance('Facade'))
                ->$method(...$arguments);
   }

}

 

Look this is the key point to create our facades. Laravel do exactly same thing to give us facades helper. By using magic method __callStatic() we will get static interface without calling a method static. Let's see.

 

Read also : How to Create and Use Custom Facade in Laravel

 

Now bind helper in service provider.

App\Providers\AppServiceProvider.php


namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helper;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        
    }

    public function boot()
    {
        $this->app->singleton('Facade', function ($app) {
            return new Helper();
        });
    }
}

 

Wow, all are set to go. We have implemented our custom facades class without the help of extendable facades class. Now you can access this hello method statically like below.

use App\Facade;
use Illuminate\Support\Facades\Route;

Route::get('facade',function(){
    Facade::hello();
});

 

Read also : ReFactoring Helper Functions to Static Class Methods In Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.