Creating Custom Facades in Laravel
Custom Facades provide a static interface to a class that gives access to an object from the service container, let’s look at Laravel’s Custom Facades.
You can define a facade simply by using getFacadeAccessor
method for a facade class.
In this post will create a custom facade in Laravel by following below few short steps.
- Create a PHP class file
- Bind that class to Service Provider
- Register that Service Provider in
Config\app.php
- Create a class that extends Illuminate\Support\Facades\Facade
- Register your facade in
Config\app.php
as aliases
So let’s get started to create an awesome facade.
Step1
Create a PHP helper class Larashout.php
in App\Larashout
. You can create a folder of your own choice instead of Larashout.
namespace App\Larashout; class Larashout { public function sayHello() { echo "Hello, from Facade class."; } }
Step2
Bind this class to a Service Provider, in my case I will create a service provider by executing below command
php artisan make:provider LarashoutServiceProvider
Then add below code in register
method for binding our class.
$this->app->bind('larashout',function(){ return new Larashout(); });
So your service provider class will look like below.
namespace App\Providers; use App\Larashout; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; class LarashoutServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('larashout',function(){ return new Larashout(); }); } }
Step3
Register that service provider in config\app.php
as providers.
/* * Application Service Providers... */ App\Providers\LarashoutServiceProvider::class,
Step4
Create a file LarashoutFacade
in App\Larashout
which will extend Illuminate\Support\Facades\Facade
. For example, my class will look like below.
namespace App\Larashout;
use Illuminate\Support\Facades\Facade;
class LarashoutFacade extends Facade { protected static function getFacadeAccessor() { return 'larashout'; } }
Step5
Register class created in Step4 in config\app.php
as aliases.
'Larashout' => App\Larashout\LarashoutFacade::class
Testing
Let’s test your facade by adding a simple route which will resolve to a closure function implementing our facade class.
Route::get('/larashout', function() { Larashout::sayHello(); });
Visit your browser with the above route and you will see the hello message. I hope this post will help you to implement a custom facade.