Laravel Contracts
Laravel Contracts
Laravel Contracts — Are a set of interfaces that define the core services provided by the framework.
Serve as succinct documentation to the framework's features.
<?php
namespace App\Orders;
use Illuminate\Contracts\Cache\Repository as Cache;
class Repository
{
/**
* The cache instance.
*/
protected $cache;
/**
* Create a new repository instance.
*
* @param Cache $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}
- All of its live in their own GitHub repository.
- Unlike facades, which do not require you to require them in your class' constructor, contracts allow you to define explicit dependencies for your classes.
- Each contract has a corresponding implementation provided by the framework.
Contracts Vs. Facades
Unlike facades, which do not require you to require them in your class' constructor, contracts allow you to define explicit dependencies for your classes.
If you are building a package, you should strongly consider using contracts since they will be easier to test in a package context.
When To Use Contracts
How To Use Contracts
<?php
namespace App\Listeners;
use App\User;
use App\Events\OrderWasPlaced;
use Illuminate\Contracts\Redis\Database;
class CacheOrderInformation
{
/**
* The Redis database implementation.
*/
protected $redis;
/**
* Create a new event handler instance.
*
* @param Database $redis
* @return void
*/
public function __construct(Database $redis)
{
$this->redis = $redis;
}
/**
* Handle the event.
*
* @param OrderWasPlaced $event
* @return void
*/
public function handle(OrderWasPlaced $event)
{
//
}
}