Search code examples
phplaraveldependency-injectionfacade

Is Laravel Facades are WET code?


According to the documentation:

Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of PHP's dynamic methods, they are easy to test.

And according to this link

Disclaimer: I don't necessarily agree that facades are bad or an anti-pattern

The question. Is the Facades are WET codes?


Solution

  • There is nothing to do with wet or dry in Facade. A facade is just an extra layer on top of the service container. Facade does only one thing and that's, it provides the given name of a class that is an alias to another class, through which you can resolve the main class and it allows you to do it easily, using static method calling style even tho it's not static. Let's see an example:

    $request = app('request');
    
    $inputs = $request->all();
    

    The code above resolves the request class from the container and it can resolve it from the container because in the container, the key request is already bound/mapped to a class which will be resolved by the framework. The resolving mechanism is stored inside the container so it's possible to resolve the class. Notice, there is no facade involved then what a facade does?

    Well, if you do the same thing using the facade then you can do it using something like this:

    $inputs = Request::all();
    

    In this case, the facade for that class will be invoked and it'll resolve the underlying class. There are mainly two steps for that:

    1 . Get the alias name for that and in this case request

    2 . Resolve the class using the alias, i.e: app('request')

    So, what it does for you is that, actually the facade itself makes the call app('request') for you but only extra thing it does is that, it finds out the alias name first so it can call it using that name from the container. A facade provides an easy entrance to a class (or a building). Hope I answered your question. For more, read about the facade in the documentation.