代码之家  ›  专栏  ›  技术社区  ›  Jan Richter

laravel-使用cachemanager作为依赖项

  •  1
  • Jan Richter  · 技术社区  · 6 年前

    我想用 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)
        );
    });
    

    问题是当我试图使用我的服务时,拉维尔无法解决 缓存管理器 类(有一些替换 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 回复  |  直到 6 年前
        1
  •  1
  •   Brian Lee    6 年前

    当应用程序有多个接口实现时, 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();
                   });
    }