Facades in Laravel

Facades in Laravel

Laravel have Facades concept that solve long underlying classes problem and give you to write more cleaner code. If you reading this guide you used facades and looking for clear the concept about facades.

Concept of Facades in Laravel

Facades provide a “static” interface to classes that are available in the application’s service container.

By Laravel

As per Laravel documentation its a class that provide static interface from your service container. As per last guide about Service Container and Service Provider we know how to create our own Service Provider where we can put our own service to Service Container.

Now If your Dependency need a more readable code you can try Facades. We can make our own Service and we will bind to service container and then we will make Facade for that particular class to make concept clear.

TestService.php

PHPCopy
<?php


namespace App\Service;


use Illuminate\Support\Str;

class TestService
{
    /**
     * @var Str
     */
    private $str;

    /**
     * TestService constructor.
     * @param Str $str
     */
    public function __construct(Str $str)
    {

        $this->str = $str;
    }

    /**
     * @param int $length
     * @return string
     */
    public function randomChar($length = 16): string
    {
        return $this->str->random($length);
    }
}

TestServiceProvider.php

PHPCopy
<?php

namespace App\Providers;

use App\Service\TestService;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class TestServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(TestService::class, function () {
            return new TestService(new Str());
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

config/app.php

PHPCopy
'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

        \App\Providers\TestServiceProvider::class // added here

    ],

TestServiceFacade.php

PHPCopy
<?php


namespace App\Facades;


use App\Service\TestService;
use Illuminate\Support\Facades\Facade;

class TestServiceFacade extends Facade
{
    public static function getFacadeAccessor(): string
    {
        return TestService::class;
    }
}

now every thing is done and have to check that our code is working or not so i just put it in routes/web.php file and open route in browser.

PHPCopy
Route::get('/', function () {
    return \App\Facades\TestServiceFacade::randomChar();
});

I got result. now its your turn to check the result in your system because without doing you can’t experience what going here.

Conclusion

Facades have many benefits. Like its allows to use without remembering long class names that must be injected or configured manually. While using facade you need to careful because primary problem of facade is scope creep because it is easy to use and you can think about grow your class with more functionality. ( Greed is bad 😂 ).

Leave a Comment