在Laravel 5中将缓存注入为依赖项

Cra*_*aig 3 caching laravel-5

我想摆脱使用Cache Facade并使用构造函数将其注入我的控制器,如下所示:

use Illuminate\Contracts\Cache\Store;

...

protected $cache;

public function __construct(Store $cache)
{
    $this->cache = $cache;
}
Run Code Online (Sandbox Code Playgroud)

然后我在AppServiceProvider.php中使用app绑定.

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

但是,我收到以下错误,因为FileStore.php需要构造函数中的$ files和$ directory参数.

Container.php第872行中的BindingResolutionException:类Illuminate\Cache\FileStore中无法解析的依赖项解析[Parameter#1 [$ directory]]

知道如何解决这个问题吗?

luk*_*ter 15

如果你想使用等效的Cache外观,你应该注入Illuminate\Cache\Repository:

use Illuminate\Cache\Repository as CacheRepository;

// ...

protected $cache;

public function __construct(CacheRepository $cache)
{
    $this->cache = $cache;
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中查找外观的基础类:

外墙 - 门面类参考

  • 谢谢!我希望Laravel文档能够扩展如何注入服务,而不是依赖于更先进的开发人员的外观.当您尝试将模块提取到包中时,它会派上用场. (3认同)