Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between contracts and facades laravel

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?

like image 718
ujwal dhakal Avatar asked Nov 23 '15 14:11

ujwal dhakal


People also ask

What are contracts in Laravel?

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.

What are facades in Laravel?

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.

What is the use of facades?

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.


1 Answers

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

  • A contract is an interface (here is an example)
  • A contract is used to load a class from service container more convenient AND as an interface
  • The class that is going to be loaded is determined in the service container, see Binding Interfaces To Implementations

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();
like image 112
Adam Avatar answered Sep 17 '22 13:09

Adam