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
- 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
| Contract | Interface |
|---|---|
Illuminate\Contracts\Auth\Authenticatable | User auth model (e.g., User) |
Illuminate\Contracts\Queue\Queue | Queues |
Illuminate\Contracts\Cache\Repository | Cache repository |
Illuminate\Contracts\Mail\Mailer | Mail sending |
Illuminate\Contracts\Filesystem\Filesystem | File storage (disk) |
Illuminate\Contracts\Broadcasting\Broadcaster | Broadcasting 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.
