Contracts

Introduction

Laravel's Contracts are a set of interfaces that define the core services provided by the framework. For example, a Illuminate\Contracts\Queue\Queue contract defines the methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed for sending e-mail.

Each contract has a corresponding implementation provided by the framework. For example, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by SwiftMailer.

All of the Laravel contracts live in their own GitHub repository. This provides a quick reference point for all available contracts, as well as a single, decoupled package that may be utilized by package developers.

Contracts Vs. Facades

Laravel's facades provide a simple way of utilizing Laravel's services without needing to type-hint and resolve contracts out of the service container. However, using contracts allows you to define explicit dependencies for your classes. For most applications, using a facade is just fine. However, if you really need the extra loose coupling that contracts can provide, keep reading!

Why Contracts?

You may have several questions regarding contracts. Why use interfaces at all? Isn't using interfaces more complicated? Let's distil the reasons for using interfaces to the following headings: loose coupling and simplicity.

Loose Coupling

First, let's review some code that is tightly coupled to a cache implementation. Consider the following:

  1. <?php
  2. namespace App\Orders;
  3. class Repository
  4. {
  5. /**
  6. * The cache instance.
  7. */
  8. protected $cache;
  9. /**
  10. * Create a new repository instance.
  11. *
  12. * @param \SomePackage\Cache\Memcached $cache
  13. * @return void
  14. */
  15. public function __construct(\SomePackage\Cache\Memcached $cache)
  16. {
  17. $this->cache = $cache;
  18. }
  19. /**
  20. * Retrieve an Order by ID.
  21. *
  22. * @param int $id
  23. * @return Order
  24. */
  25. public function find($id)
  26. {
  27. if ($this->cache->has($id)) {
  28. //
  29. }
  30. }
  31. }

In this class, the code is tightly coupled to a given cache implementation. It is tightly coupled because we are depending on a concrete Cache class from a package vendor. If the API of that package changes our code must change as well.

Likewise, if we want to replace our underlying cache technology (Memcached) with another technology (Redis), we again will have to modify our repository. Our repository should not have so much knowledge regarding who is providing them data or how they are providing it.

Instead of this approach, we can improve our code by depending on a simple, vendor agnostic interface:

  1. <?php
  2. namespace App\Orders;
  3. use Illuminate\Contracts\Cache\Repository as Cache;
  4. class Repository
  5. {
  6. /**
  7. * The cache instance.
  8. */
  9. protected $cache;
  10. /**
  11. * Create a new repository instance.
  12. *
  13. * @param Cache $cache
  14. * @return void
  15. */
  16. public function __construct(Cache $cache)
  17. {
  18. $this->cache = $cache;
  19. }
  20. }

Now the code is not coupled to any specific vendor, or even Laravel. Since the contracts package contains no implementation and no dependencies, you may easily write an alternative implementation of any given contract, allowing you to replace your cache implementation without modifying any of your cache consuming code.

Simplicity

When all of Laravel's services are neatly defined within simple interfaces, it is very easy to determine the functionality offered by a given service. The contracts serve as succinct documentation to the framework's features.

In addition, when you depend on simple interfaces, your code is easier to understand and maintain. Rather than tracking down which methods are available to you within a large, complicated class, you can refer to a simple, clean interface.

Contract Reference

This is a reference to most Laravel Contracts, as well as their Laravel "facade" counterparts:

ContractReferences Facade
Illuminate\Contracts\Auth\GuardAuth
Illuminate\Contracts\Auth\PasswordBrokerPassword
Illuminate\Contracts\Bus\DispatcherBus
Illuminate\Contracts\Broadcasting\Broadcaster
Illuminate\Contracts\Cache\RepositoryCache
Illuminate\Contracts\Cache\FactoryCache::driver()
Illuminate\Contracts\Config\RepositoryConfig
Illuminate\Contracts\Container\ContainerApp
Illuminate\Contracts\Cookie\FactoryCookie
Illuminate\Contracts\Cookie\QueueingFactoryCookie::queue()
Illuminate\Contracts\Encryption\EncrypterCrypt
Illuminate\Contracts\Events\DispatcherEvent
Illuminate\Contracts\Filesystem\Cloud
Illuminate\Contracts\Filesystem\FactoryFile
Illuminate\Contracts\Filesystem\FilesystemFile
Illuminate\Contracts\Foundation\ApplicationApp
Illuminate\Contracts\Hashing\HasherHash
Illuminate\Contracts\Logging\LogLog
Illuminate\Contracts\Mail\MailQueueMail::queue()
Illuminate\Contracts\Mail\MailerMail
Illuminate\Contracts\Queue\FactoryQueue::driver()
Illuminate\Contracts\Queue\QueueQueue
Illuminate\Contracts\Redis\DatabaseRedis
Illuminate\Contracts\Routing\RegistrarRoute
Illuminate\Contracts\Routing\ResponseFactoryResponse
Illuminate\Contracts\Routing\UrlGeneratorURL
Illuminate\Contracts\Support\Arrayable
Illuminate\Contracts\Support\Jsonable
Illuminate\Contracts\Support\Renderable
Illuminate\Contracts\Validation\FactoryValidator::make()
Illuminate\Contracts\Validation\Validator
Illuminate\Contracts\View\FactoryView::make()
Illuminate\Contracts\View\View

How To Use Contracts

So, how do you get an implementation of a contract? It's actually quite simple.

Many types of classes in Laravel are resolved through the service container, including controllers, event listeners, middleware, queued jobs, and even route Closures. So, to get an implementation of a contract, you can just "type-hint" the interface in the constructor of the class being resolved.

For example, take a look at this event listener:

  1. <?php
  2. namespace App\Listeners;
  3. use App\User;
  4. use App\Events\NewUserRegistered;
  5. use Illuminate\Contracts\Redis\Database;
  6. class CacheUserInformation
  7. {
  8. /**
  9. * The Redis database implementation.
  10. */
  11. protected $redis;
  12. /**
  13. * Create a new event handler instance.
  14. *
  15. * @param Database $redis
  16. * @return void
  17. */
  18. public function __construct(Database $redis)
  19. {
  20. $this->redis = $redis;
  21. }
  22. /**
  23. * Handle the event.
  24. *
  25. * @param NewUserRegistered $event
  26. * @return void
  27. */
  28. public function handle(NewUserRegistered $event)
  29. {
  30. //
  31. }
  32. }

When the event listener is resolved, the service container will read the type-hints on the constructor of the class, and inject the appropriate value. To learn more about registering things in the service container, check out its documentation.