ホーム > Laravel > What is Facade in Laravel? Implementation of Facade
Laravel

What is Facade in Laravel? Implementation of Facade

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents of Laravel articles

This article explains what Facade in Laravel is and also covers the implementation method. It is aimed at those who have no idea about Facade.

What is a Facade?

A Facade is a feature that allows classes to be easily called.

Have you ever thought,

use App\Models\Post; // Why do I have to write the full path for the model
use Auth; // Isn't this enough for Auth?

Facade functionality allows you to write this in a shortened form.

Implementation of Facade

We will go through using a service class as a Facade.

The service class we will use this time is being reused from another article.

If you are unfamiliar with service classes, please refer to this article.

How to Use Service Classes in Laravel

Registering in the Service Container

app/Providers/AppServiceProvider.php

use App\Services\Test;

// Omitted part

public function register() {
    app()->bind('Test', Test::class);
}

Creating a Facade Class

Create App\Facades\TestFacade.php and write the following code. Also, create a Facades directory.

<?php

namespace App\Facades;
use Illuminate\Support\Facades\Facade;

class TestFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'Test';
    }
}

Calling the Facade

In a controller or similar,

use App\Facades\TestFacade; // Use it

// Omitted
public function index()
{
  $user = TestFacade::getTestUser();
  dd($user);
}

This is how you can call it.

Registering the alias

By registering an alias, you can omit the "use" statement.

This setting can be done in /config/app.php.

'aliases' => [
  // Add at the end after a lot of statements
  'Test' => App\Facades\TestFacade::class,
]

After adding to config, load the changes

php artisan config:clear
or,
php artisan config:cache

Calling the Facade registered with the alias

  $user = \Test::getTestUser();
  dd($user);

By starting with

\

you can call it without using the "use" statement. Pretty convenient, right?

Summary

That's all.

This article explained how to implement the Facade feature in Laravel.

I hope it can be a reference for someone.

For feedback or complaints, please contact me via Twitter DM.

Until next time!

Popular Articles

Deploying PHP7.4 + Laravel6 Project to AWS EC2

Implementing Breadcrumbs in Laravel with laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!