One of the things that that facades have going for them, is that they are elegant to look at it. But in my view, they hide the core logic, and make it difficult to understand how exactly a class works. Often times, when debugging, you need to look at the implementation of a method because it’s not documented.
Something that I believe is not documented and encouraged well enough is using Dependency Injection instead of Facades all over your codebase. I want to start with an example of a “before” and “after” class that used Facades, but now uses DI. For all internal Laravel services, and classes, such as the encryption class, you can see the mapping from interface to implementation in the Illuminate\Foundation\Application class. You can use this as a reference when replacing facades with Dependency Injection.
So with the above setup, you do not have to do any configuration, or service binding because Laravel will automatically instantiate your instances for you through it’s container. The registerCoreContainerAliases method on the
Illuminate\Foundation\Application class is the source of truth for these Facade to container aliases. The format is as follows:
As we can see the first element of each array is the implementation, while the second element is the interface. For example on line 17,
encrypter is mapped to interface
\Illuminate\Contracts\Encryption\Encrypter::class from core implementation
This post was brought to you by Amezmo – Where we make it easy to spin up a new PHP container for your application and deployment. Try us out for free using promo code FRIEND.