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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay