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";
}
}
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();
});
}
}
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;
}
}
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);
Top comments (0)