Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting cache as a dependency in Laravel 5

I'd like to get away from using the Cache facade and inject it into my controller using the constructor, like this:

use Illuminate\Contracts\Cache\Store;

...

protected $cache;

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

I'm then using an app binding in AppServiceProvider.php.

public function register()
{
    $this->app->bind(
        'Illuminate\Contracts\Cache\Store',
        'Illuminate\Cache\FileStore'
    );
}

However, I get the following error because FileStore.php expects $files and $directory parameters in the constructor.

BindingResolutionException in Container.php line 872: Unresolvable dependency resolving [Parameter #1 [ $directory ]] in class Illuminate\Cache\FileStore

Any idea how I would get around this?

like image 279
Craig Avatar asked Dec 02 '22 14:12

Craig


1 Answers

If you want to use the equivalent of the Cache facade you should inject Illuminate\Cache\Repository instead:

use Illuminate\Cache\Repository as CacheRepository;

// ...

protected $cache;

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

You can look up the underlying classes of facades in the documentation:

Facades - Facade Class Reference

like image 72
lukasgeiter Avatar answered Dec 06 '22 07:12

lukasgeiter