Hion Coding - Blogs share everything
  • HOME
  • ABOUT
  • POSTS
  • CONTACT
  • TOOLS
    CÂU HỎI VÕ ĐÀI TỐI THƯỢNG CONVERT IMAGE TO WEBP
Elevating Junior Laravel Developers: Learn about Facade

Elevating Junior Laravel Developers: Learn about Facade

Hion Coding - Blogs share everything
Admin Hion Coding Blogs vochilong.work@gmail.com
3rd January 2024

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Facade

Reference: Viblo

Index Elevating Junior Laravel Developers
 series:

  1. Elevating Junior Laravel Developers: Recipes & Best Practices
  2. Elevating Junior Laravel Developers: Learn about Service containers
  3. Elevating Junior Laravel Developers: Learn about Service Provider
  4. Elevating Junior Laravel Developers: Learn about Facade
  5. Elevating Junior Laravel Developers: Learn about Contract


Through previous articles in the Laravel Beauty series, I introduced to you two basic concepts used in Laravel: Service Container and Service Provider. These are two central concepts that need to be mastered when wanting to learn deeply about other functions of Laravel.

In this article, we will learn about a feature that you have probably used, and still often use, in your projects, and it can only be explained with an understanding of Service Containers as well as Services. Provider. So if you still do not clearly understand the above two concepts, please take some time to review the previous articles in this Laravel Beauty series.
 

What is Facade?

If you like learning about Design Patterns and have seen the famous book Design Patterns: Elements of Reusable Object-Oriented Software by "Gang of Four", then you may know Facade Pattern, which is in the Structural group.
However, the concept of Facade in Laravel... has absolutely nothing to do with the Facade Pattern mentioned in Gang of Four's book. Introducing this so you won't get confused later.

Let's take a look at the config/app.php file a bit.

If you pay attention to the end of that config file, you will see that Laravel has already declared a series of class aliases, so that we can later use them in our project under a short name, instead of having to write the full namespace. of them. That is, when there is a declaration 'Auth' => Illuminate\Support\Facades\Auth::class, then when we use the Auth class inside our project, we actually call the Illuminate\Support\Facades\Auth.
If you wonder why Laravel can do such a seemingly "divine" job, it's actually nothing special, because PHP itself already supports us with that feature through the class_alias function. Your job is just to declare the alias as a key-value in the config/app.php file, while registering the alias through the class_alias function will be done by Laravel. You can refer to the Illuminate\Foundation\AliasLoader class to understand the nature of this process.

Going back to the issue of registering an alias in the config file, what does it have to do with the Facade theme?

Did you notice the full names of the registered aliased classes? Yes, they all have the namespace Illuminate\Support\Facades. In other words, the classes registered as aliases here are all Facades. Laravel's default Facades are located in the vendor\laravel\framework\src\Illuminate\Supports folder.
In addition, the aliases that you may often use, such as App, Auth, DB, Route... are all Facade.
For example, these familiar lines of code:

// routes.php file
Route::get('/', function () {
    return view('welcome');
});

// Controller file
if (Auth::check()) {
    $user = Auth::user();
}

Yes, when you call the Route::get(), or Auth::user() functions as above, you are using Facade. Is it true that you are using static functions?
However, now is the time when this problem becomes complicated. Let's try to see the content of a Facade file.
For example, Auth Facade. This is all you see in the Illuminate\Support\Facades\Auth class

namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Auth\AuthManager
 * @see \Illuminate\Contracts\Auth\Factory
 * @see \Illuminate\Contracts\Auth\Guard
 * @see \Illuminate\Contracts\Auth\StatefulGuard
 */
class Auth extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'auth';
    }
}

There is only one method in that class, named getFacadeAccessor, and there is absolutely no other static method at all. So where do the functions Auth::check(), Auth::user(), or Auth::id() come from?


How does Facade work?

Now we will continue to learn the ins and outs of a Facade class. Pay attention a bit, we see that the Auth class, or other Facade classes, all inherit from an abstract class Illuminate\Support\Facades\Facade. In this class we will see the function getFacadeAccessor()

/**
 * Get the registered name of the component.
 *
 * @return string
 *
 * @throws \RuntimeException
 */
protected static function getFacadeAccessor()
{
    throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
}

Declaring a method with the only content of throw error like this means your inherited class must declare override the getFacadeAccessor() function (otherwise there will be an error). Therefore, all Facades will have a static method called getFacadeAccessor() (and luckily, Laravel does everything for us, to the point that each Facade just needs to have that one function).
Carefully read the content of the abstract class Facade and you will see that the content returned by the getFacadeAccessor() method will be used to create a Facade Instance, which is resolved from Application Instance $app, or in other words, Service Containers.

So working with Auth Facade is actually working with service auth in Service Container. The actual calling of Auth's static functions will be handled in the magic method __callStatic (you can learn about this magic method here), then transferred to a normal function call from an instance that has been resolved from within the Service Container.

So we can see that the following calls are equivalent:

Auth::check();

$auth = app('auth');
$auth->check();


Facade - the Good and the Bad

  • Facade can be said to be one of the most controversial concepts or features of Laravel. You can google a bunch of articles, saying that Facade is a "Bad design", or "Anti-pattern". But there are many people who still love and use Facade every day. It was and still is a part of Laravel.
  • Facade is convenient. Facade is easy to use. Facade helps you write very concise code quickly. On Laravel's documentation, Facade is described with many advantages such as "providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods".
  • Facade is designed as a bridge for programmers to easily access "Service". You can use Facade almost anytime, anywhere without having to bother creating and resolving instances from within the Service Container. Facade is essentially not a class full of static methods, so it doesn't take up as much memory as other classes like that.
  • However, to have such conveniences, we need a bunch of "magic" that are processed behind the scene. For someone who is just starting to learn and use Laravel, they will probably easily know and use calling Auth::user(), but they will not be able to understand where the nature of that function comes from. Or when you encounter problems and need to go into the Framework's code to check, it is difficult for you to find their origin.
  • Furthermore, with Facade being so convenient, if you're not careful you can make the code more complicated and unpredictable. For example, if I want to check what dependencies a class operates on, I will usually look in its constructor. Or if Laravel has support for method injection, I'll take a look at it in the method declaration as well. However, by calling Facade inside the function, we are invisibly hiding the fact that the function, or class, needs a service dependency, which instead of being injected, is now resolved through Facade.


Epilogue

Within the scope of this article, I would like to stand aside from the debate on whether or not I should use Facade. It is a handy feature and it is no coincidence that Taylor Otwell, the father of Laravel, still retains it today.

This article only hopes to help you better understand what happens behind the static functions that we often call through Facade.

As for the question "If I don't use Facade, what can I use instead?", I would answer that I still use Dependency Injection.
Hopefully, through this article, everyone can understand more about a very familiar feature of Laravel. And see you again in the next article, with a more in-depth exploration of this popular Framework
 

Reference: Viblo

Thank you! Good luck! Hion Coding


Integrating CKEditor 5 In Laravel 10 Using Vite

9th April 2024

Integrating CKEditor 5 In Laravel 10 Using Vite

PHP/Laravel

Laravel Eloquent Tips🔥 🚀

3rd January 2024

Laravel Eloquent Tips🔥 🚀

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Contract

3rd January 2024

Elevating Junior Laravel Developers: Learn about Contract

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Service Provider

3rd January 2024

Elevating Junior Laravel Developers: Learn about Service Provider

PHP/Laravel

Hion Coding - Blogs share everything


© 2025 Hion Coding DMCA.com Protection Status