Contracts

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

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

    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 other package developers.

    You may have several questions regarding contracts. Why use interfaces at all? Isn't using interfaces more complicated?

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

    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:

    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

    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.

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

    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 , including controllers, event listeners, filters, queue 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 handler: