HomeUncategorizedWhat Are Laravel Contracts

What Are Laravel Contracts

In Laravel, Contracts are a set of interfaces that define the core services provided by the framework. These are found in the Illuminate\Contracts namespace.


🔹 What Are Laravel Contracts?

Contracts are like agreements or blueprints. They specify the methods a class must implement. Laravel uses these contracts to define the behavior of various components like:

  • Cache
  • Queue
  • Mail
  • Events
  • Filesystem
  • Authentication
  • Logging, etc.

🔹 Why Use Contracts?

  • Loose coupling: You can easily swap implementations without changing the code that uses them.
  • Testing: Makes it easier to mock dependencies.
  • Cleaner code: Encourages following the SOLID principles, especially the Dependency Inversion Principle.

🔹 Example: Cache Contract

Laravel’s cache system uses the Illuminate\Contracts\Cache\Repository contract.

Interface (Contract):

use Illuminate\Contracts\Cache\Repository;

class MyService {
    protected $cache;

    public function __construct(Repository $cache) {
        $this->cache = $cache;
    }

    public function getData() {
        return $this->cache->get('key');
    }
}

Here, Laravel will inject any class that implements the Repository contract. The default is Illuminate\Cache\CacheManager.


🔹 Where Are Contracts Defined?

All contracts live in the Illuminate\Contracts namespace.

Example path:

vendor/laravel/framework/src/Illuminate/Contracts

🔹 Commonly Used Contracts

ContractInterface
Illuminate\Contracts\Auth\AuthenticatableUser auth model (e.g., User)
Illuminate\Contracts\Queue\QueueQueues
Illuminate\Contracts\Cache\RepositoryCache repository
Illuminate\Contracts\Mail\MailerMail sending
Illuminate\Contracts\Filesystem\FilesystemFile storage (disk)
Illuminate\Contracts\Broadcasting\BroadcasterBroadcasting events

🔹 Binding Contracts to Implementations

Laravel uses the service container to bind interfaces to concrete classes.

Example from AppServiceProvider:

use Illuminate\Contracts\Cache\Repository;
use App\Services\CustomCacheService;

public function register()
{
    $this->app->bind(Repository::class, CustomCacheService::class);
}

🔹 Summary

  • Contracts are interfaces that define expected functionality.
  • They promote flexibility, testability, and clean architecture.
  • Laravel provides concrete implementations and binds them automatically.
  • You can replace default services by binding your own implementations.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *