Laravel-使用CacheManager作为依赖项

时间:2018-07-02 22:48:38

标签: php laravel dependency-injection

我正在尝试使用CacheManager类作为服务中的依赖项:

<?php

declare(strict_types=1);

namespace App;

use GuzzleHttp\Client;
use Illuminate\Cache\CacheManager;

class MatrixWebService implements WebServiceInterface
{
    public function __construct(Client $client, CacheManager $cache)
    {
        $this->client = $client;
        $this->cache = $cache;
    }
}

由于WebserviceInterface可以有多种实现,因此需要在AppServiceProvider中进行相应的定义:

$this->app->bind(WebServiceInterface::class, function () {
    return new MatrixWebService(
        new Client(),
        $this->app->get(CacheManager::class)
    );
});

问题是当我尝试使用我的服务时,Laravel无法解析CacheManager类(代替cache的某些类):

[2018-07-02 22:45:26] local.ERROR: Class cache does not exist {"exception":"[object] (ReflectionException(code: -1): Class cache does not exist at /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php:769)
[stacktrace]
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(769): ReflectionClass->__construct('cache')
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(648): Illuminate\\Container\\Container->build('cache')
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(610): Illuminate\\Container\\Container->resolve('cache')
#3 /var/www/html/app/Providers/AppServiceProvider.php(28): Illuminate\\Container\\Container->get('Illuminate\\\\Cach...')
...

关于如何正确处理此问题的任何想法?

1 个答案:

答案 0 :(得分:1)

当您的应用程序具有接口的多种实现时,contextual binding会很有用:

namespace App;

use GuzzleHttp\Client;
use Cache\Repository;

class MatrixWebService implements WebServiceInterface
{
    public function __construct(Client $client, Repository $cache)
    {
        $this->client = $client;
        $this->cache = $cache;
    }
}

// AppServiceProvider.php
public function register()
{
     $this->app->bind(WebServiceInterface::class, MatrixWebServiceInterface::class);

     // bind MatrixWebService
     $this->app->when(MatrixWebService::class)
               ->needs(Repository::class)
               ->give(function () {
                   return app()->makeWith(CacheManager::class, [
                       'app' => $this->app
                   ]);
               });

     // bind some other implementation of WebServiceInterface
     $this->app->when(FooService::class)
               ->needs(Repository::class)
               ->give(function () {
                   return new SomeOtherCacheImplementation();
               });
}