Im really struggling to understand the whole concept of Contracts in Laravel 5.
Interfaces I understand the reasons for. Single responsibility I understand the reasoning. Basically I do understand why this path has been chosen, I'm just struggling with understanding the implementation.
For example the docs give us this example: <?php namespace App\Orders;
use Illuminate\Contracts\Cache\Repository as Cache;
class Repository {
/**
* Create a new repository instance.
*
* @param Cache $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}
How would I replace -- Illuminate\Contracts\Cache\Repository -- with another implementation or a mock? In my mind the name-spaced path referees directly to a contract. How and where does laravel know the actual implementation is????
After further research Im assuming, perhaps incorrectly, that Laravel resolves the actual implementation through the service providers array in config/app.php file. If someone can enlighten me?
This raises yet another question... If for example I wanted to change the cache driver in laravel to an implementation I found on github. Would I have to write some kind of adapter so that this cache driver I want to use adheres to the original Laravel contract?
that seems a little labour intensive?
You don't replace Illuminate\Contracts\Cache\Repository, you implement a concrete class if you want another implementation of it.
If you have a look at the framework, it uses file
as its default cache implementation, using Illuminate\Cache\FileStore
a concrete implementation of the Illuminate\Cache\StoreInterface
contract (interface).
The contract merely describes the methods that that concrete class must implement, in order to be compatible with Laravel.
It may appear labour intensive on the surface, but it saves you time as it guarantees that your implementation will work with Laravel, as you know exactly what methods you need to implement at the outset. You could then package it up with a Laravel-specific service provider and facade.
That's awesome.
The only problem I have with that is integrating 3rd party composer packages that have been written framework agnostic.
In this case I would have to create an adapter to fit in with laravel. Is that assumption correct?
That assumption is correct, yeah. And it is a very clean, object-oriented and simple way to do so. =)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community