Lumen Cache\Store 不可实例化

Lumen Cache\Store is not instantiable

我是 Laravel 和 Lumen 的新手,所以我的问题可能有点简单,但我还没有找到任何有用的答案。

Lumen 版本为 5.1

所以我尝试创建一个缓存支持的数据存储库。首先我想使用FileStore,然后我想移动到一些更合适的。

我试过像这样注入缓存存储库:

<?php

    namespace App\Repositories;

    use Illuminate\Cache\Repository;

    class DataRepository
    {
        private $cache;

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

这对我来说似乎很简单。但是当我尝试在我的控制器中使用这个 repo,并试图将这个 repo 注入其中时,在实例化过程中我收到以下错误:

BindingResolutionException in Container.php line 749:
Target [Illuminate\Contracts\Cache\Store] is not instantiable.

我猜存储库找不到匹配且可用的存储实现。当我尝试像这样将 Store 绑定到 \Illumante\Cache\FileStore 时:

$this->app->bind(\Illuminate\Contracts\Cache\Store::class, \Illuminate\Cache\FileStore::class);

我遇到了一种新的错误:

Unresolvable dependency resolving [Parameter #1 [ <required> $directory ]] in class Illuminate\Cache\FileStore

我想我有一个更复杂的配置问题,所以我不想遍历依赖关系树。

在我的 .env 我有这些:

CACHE_DRIVER=fileSESSION_DRIVER=file

在 Lumen 中,我明确启用了外观、DotEnv(以及 eloquent 也用于我的数据存储库)。

Dotenv::load(__DIR__.'/../');

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->withFacades();
$app->withEloquent();

我尝试添加一个 cache.php 配置。在 bootstrap/app.php 中,我添加了 $app->configure('cache'); 以将其与以下配置一起使用:

<?php

return [
    'default' => env('CACHE_DRIVER', 'file'),

    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => storage_path('framework/cache'),
        ],
    ],
];

你能帮我吗,我怎样才能bootstrap正确缓存?

回答

Lumen中的缓存实现注册为:

Illuminate\Contracts\Cache\Repository

不是

Illuminate\Cache\Repository

因此您可以将代码更改为:

<?php

namespace App\Repositories;

use Illuminate\Contracts\Cache\Repository;

class DataRepository
{
    private $cache;

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

P.S You don't need to configure cache, since Lumen will configure any cache configuration automatically.

技巧

但如果您仍想使用 Illuminate\Cache\Repository,您可以先在 ServiceProviderbootstrap/app.php 文件中绑定它:

use Illuminate\Cache\Repository as CacheImplementation;
use Illuminate\Contracts\Cache\Repository as CacheContract;

$app->singleton(CacheImplementation::class, CacheContract::class);