caching - Lumen Cache\Store 不可实例化

标签 caching laravel-5 lumen

我对 Laravel 和 Lumen 还很陌生,所以我的问题可能有点简单,但我还没有找到任何有用的答案。

流明版本为5.1

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

我尝试像这样注入(inject)缓存存储库:

<?php

    namespace App\Repositories;

    use Illuminate\Cache\Repository;

    class DataRepository
    {
        private $cache;

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

对我来说这似乎很简单。但是,当我尝试在 Controller 中使用此存储库并尝试将此存储库注入(inject)其中时,在实例化期间出现以下错误:

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

我猜测存储库找不到匹配且可用的存储实现。当我尝试将 Store 绑定(bind)到\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 中,我明确启用了 Facade、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'),
        ],
    ],
];

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

最佳答案

回答

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 中绑定(bind)它> 文件:

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

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

关于caching - Lumen Cache\Store 不可实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37945911/

相关文章:

php - 从两个表中获取唯一结果或如何按 ID 在 laravel 中减去两个表

laravel - Lumen 自定义验证响应

caching - 维护包含 ESI 的请求的 session

java - 如何让 Infinispan 与 Camel 一起工作

caching - 为什么 nginx 不缓存我的内容?

linux - 了解 linux `free -m` 中的缓冲区/缓存

php - laravel 5 查询急切加载的多重约束

laravel - 在 WITH 子句中使用 SELECT 急切加载关系返回空

php - 通过浏览器访问 IP 地址时,在 nginx 上创建新的 Lumen 应用程序会抛出 404

docker - Kubernetes - 通过 ssh 连接到远程数据库服务器