A Guide to Using Laravel Facades: Simplify Your Laravel Code
Laravel facade is one of most important topics to learn to use this framework. Understanding facade will help in many cases when developing applications in this framework. Facades provide a very simple and developer-friendly interface when coding. You have seen or used functions like Request::all() for example, these are actually facades. Laravel provides a lot of built in facades ready to use after installation. But alongside that, we can also create our own custom facades for convenience. In this article, we will an example how we can achieve that.
What are facades?
Facades works like wrapper for non-static functions, to make them static. In addition, they are the classes for which you can access the methods anywhere you want, without instantiating the class or making an object. Just like a static method.
Lets create a custom facade for our own application
First, create a service class that we will use as Facade. Create a file CustomService.php under app/Services:
namespace App\Services;
class CustomService
{
public function doSomething()
{
return 'Doing something!';
}
}
Now we will make facade for this service. Under app/Facades directory, lets create a file named CustomFacade.php
// app/Facades/CustomFacade.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class CustomFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'customservice';
}
}
After creating the facade, we need to bind that with our service created. You can do that in AppServiceProvider like this:
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\CustomService;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('customservice', function () {
return new CustomService();
});
}
}
Done, now you should be able to access the facade anywhere from your application:
use App\Facades\CustomFacade;
// Accessing the custom service through the facade
CustomFacade::doSomething();
That simple it is to create a custom facade to use for yourself. Please give it a try if you havent done before.
Thanks for paying time in this post. Let me know your thoughts in the comments and please give a love to this article if you find it helpful.
Wish you a happy day.
Comments