Web Development Handbook

Web Development Handbook

Development is fun in a funny way

How to create Facade in Laravel: A beginner guide

How to create Facade in Laravel: A beginner guide

1 vote
0 votes
0 comments
425 views
Share

By Nihar Ranjan Das, Published on May 20th 2023 | 9 mins, 810 words

We all know Laravel is one of the awesome frameworks for web development and Facade is one of the cool design patterns in Laravel. Here, In this article, we will learn about Facade.

In the early stage of my Laravel development journey, I was so confused and amazed while using some Laravel classes for learning purposes. Like Storage, Cache, DB, etc. I was so curious, about how those classes work. It takes a lot of my time to understand it properly. In this article, we will learn about facades and hope, you will not face any confusion about Laravel facades.

In this article, we will cover those

  • What are facades?
  • How does it work in Laravel?
  • How we can build our own facade and use it in Laravel?


What are facades?

A facade is a structural design pattern that provides a static interface of a class. It wraps a non-static class and turns it into a static class.

Before start learning more about facades, we need a clear understanding of static and non-static methods in PHP.

Static Methods & Properties

In the PHP class, we can call a static method or access a static property without creating an interface for that class. To call or access a static method or property, We need to use double colons(::) and all static properties or classes must have a static keyword before the variable or method name.

Let's see some examples.

class Circle
{
    public string $PI = '3.1419';
}

echo Circle::$PI; // 3.1419

Here we access a static property called $PI without creating an instance of the Circle class.

class Laravel
{
    private static string $lang = 'PHP';
    public static function language(): string
    {
        return self::$lang;
    }
}

echo Laravel::language(); // PHP

Here we get the value of $lang variable using a static method called language.

No-static methods or properties

On the other hand, To access no-static methods or properties need to initiate the given class first. In short, We can access non-static properties from a given class instance.

Let's see some examples.

class Circle
{
    public static string $pi = '3.1419';

    public function area(float $r): float
    {
        return self::$pi * $r * $r;
    }
}

$circle = new Circle();
echo $circle->area(2.5); // 19.636875

In this example, we have the Circle class, which has a non-static method called area. To call the area method, first, we need to create an instance of the Circle class called $circle. We need to use arrow(->) key.

Now, we have got enough idea about static and non-static methods, let's dive deeper into Laravel facades.


Facades in Laravel?

There is a whole list of facades already developed and widely used in Laravel. Here is a screenshot of where those facades exiting in the Laravel source code.

vendors > laravel > framework > src > illuminate > support > Facades
Let's explore one of those facade classes and talk about that in detail.

DB facade of Laravel

Here is the code of the DB facade

<?php

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

Here we see, The DB facade extends an abstract class called Facade which is the base class. There is also a static method called getFacadeAccessor which returns db. getFacadeAccessor method basically determines what needs to resolve from the app container. The Facade base class has a magic method called __callStatic(), which calls the resolved object.


How we can create a custom facade in Laravel?

We can easily create our own facade in Laravel. For this, According to Laravel documentation, we need to follow three steps:

  1. An ioC (inversion of control) binding 
  2. A facade class
  3. A facade alise configuration 

Let's look at an example. Here we have a class App\PaymentGatway\Payment

namespace App\PaymentGateway;
 
class Payment 
{
    public function process()
    {
        //
    }
}

Now we need to bind this class in ioC container. For this, a great place to register this binding would be to create a new service provider named PaymentServiceProvider and add the binding to the register method.

namespace App\Providers;

use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;

class PaymentServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        App::bind('payment', function()
        {
            return new \App\PaymentGateway\Payment;
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Next, we need to create our own facade class.

namespace App\Facades;

use Illuminate\Support\Facades\Facade;
 
class Payment extends Facade 
{
    protected static function getFacadeAccessor() { 
        return 'payment'; 
    }
}

After creating the facade class, we need to add an alias for our facade class in the config/app.php file. Now we can call the process method statically using the Payment facade.

Payment::process();

This is the way, how we can create a custom facade in Laravel. Hope this article will help you to understand the facade pattern in Laravel. If you have any questions or if I miss something, please let me know in the comment.

If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.