How Facade Works in Laravel Create an Example

tutspack laravel
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Artisans,

How are you doing? In this tutorial, I will show you how to Laravel facades work. You will able to know that how Laravel facades work. In this example, we will create our own custom facades class. So here we go.

You know that Laravel facades give us a static interface. That means we can call a method directly without creating an object. If you don’t know how to create Laravel facades you are in the right place, this tutorial is going to be helpful for you.

How Facade Works in Laravel Create an Example

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 test()
    {
        return "this is a custom facade class";
    }
}

Look this is the helper class and test() 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 : CRUD Example with Repository Design Pattern in Laravel

Now time to 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();
        });
    }
}

Well, our all setup has ready. 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::test();
});

Output : this is a custom facade class


Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published. Required fields are marked *