DEV Community

vimuth
vimuth

Posted on • Edited on

Laravel Facades.

Let us create a custom facade.

Suppose you have a class PaymentGateway that you want to access through a facade.

1. Create the Class:

namespace App\Services;

class PaymentGateway
{
    public function process($amount)
    {
        return "Processing payment of $amount";
    }
}

Enter fullscreen mode Exit fullscreen mode

2. Bind to Service Container:
Register the service in a service provider, typically in the register method of AppServiceProvider:

use App\Services\PaymentGateway;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(PaymentGateway::class, function ($app) {
            return new PaymentGateway();
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Create the Facade:
Create a new facade by extending Illuminate\Support\Facades\Facade:

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Payment extends Facade
{
    protected static function getFacadeAccessor()
    {
        return PaymentGateway::class;
    }
}

Enter fullscreen mode Exit fullscreen mode

Make note that we hasn't added a use statement like this.
use App\Services\PaymentGateway; Reason is the getFacadeAccessor method typically returns the class identifier as a string. Laravel uses this string to look up the class in its service container. Since it's a string and not a direct class reference, there's no need to import the class with a use statement.

4. Using the Facade:
You can now use the facade anywhere in your Laravel application:

use App\Facades\Payment;

Payment::process(100);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)