I have been doing laravel since 4 months. I don't find a clear difference between facades and contracts as they both are set of interfaces. Why would i use facades instead of contracts or contracts instead of facades?
Laravel's Contracts are a set of interfaces that define the core services provided by the framework. For example, a Queue contract defines the methods needed for queueing jobs, while the Mailer contract defines the methods needed for sending e-mail.
In a Laravel application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the Facade class. Laravel's facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class. * Show the profile for the given user.
A facade is a class wrapping a complex library to provide a simpler and more readable interface to it. Facades provide a "static" interface to classes that are available in the application's service container.
The question whether to use Facade
or Contract
boils down how you want to resolve your classes and if you want to use interfaces.
Facade
A facade is a class and not an interface (here is an example facade).
A facade is only used to load a class from service container more convenient
The class that is going to be loaded is determent in the getFacadeAccessor()
method of the facade class.
Example:
// Without facade - resolving from service container
app('some_service')->methodName();
// Do the same through facade:
someService::methodName();
Contract
Example: Assuming that class some_service
implements interface Illuminate\Contracts\Config\Repository
:
// resolving class directly from service container
app('some_service')->methodName();
// resolve through binding from contract
app('Illuminate\Contracts\Config\Repository')->methodName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With