根据环境自动装配symfony CacheInterface

tho*_*ron 2 php caching autowired symfony psr-6

我试图在我的环境中使用不同的缓存系统.我想有,例如,Filesystem用于开发memcached进行督促.

我正在使用symfony 3.3.10.

为实现这一目标,我想将CacheInterface自动装配如下:

use Psr\SimpleCache\CacheInterface;

class Api {

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

这是我的配置文件:

config_dev.yml:

framework:
    cache:
        app: cache.adapter.filesystem
Run Code Online (Sandbox Code Playgroud)

config_prod.yml:

framework:
    cache:
        app: cache.adapter.memcached
        ...
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误: 在此输入图像描述

FilesystemCache声明为服务时,错误消失:

services:
    Symfony\Component\Cache\Simple\FilesystemCache: ~
Run Code Online (Sandbox Code Playgroud)

但是现在我不能为NullCache这样的测试环境建立另一个缓存系统.实际上,我只需要声明一个继承自CacheInterface的服务.这是不可能config_test使用config_dev了.

这是services.yml的开始,如果它可以帮助:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
Run Code Online (Sandbox Code Playgroud)

有关如何根据环境自动装配不同缓存系统的任何想法?

编辑:

这是工作配置:

use Psr\Cache\CacheItemPoolInterface;

class MyApi
{
    /**
     * @var CacheItemPoolInterface
     */
    private $cache;

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

config.yml:

framework:
    # ...
    cache:
        pools:
            app.cache.api:
                default_lifetime: 3600
Run Code Online (Sandbox Code Playgroud)

services.yml:

# ...
Psr\Cache\CacheItemPoolInterface:
    alias: 'app.cache.api'
Run Code Online (Sandbox Code Playgroud)

yce*_*uto 5

尽管工厂模式是解决此类问题的一个很好的选择,但通常您不需要为Symfony缓存系统执行此操作.Typehints CacheItemPoolInterface代替:

use Psr\Cache\CacheItemPoolInterface;

public function __construct(CacheItemPoolInterface $cache)
Run Code Online (Sandbox Code Playgroud)

它会cache.app根据活动环境自动注入当前服务,因此Symfony会为您完成工作!

只需确保framework.cache.app为每个环境配置文件配置:

# app/config/config_test.yml
imports:
    - { resource: config_dev.yml }

framework:
    #...
    cache:
        app: cache.adapter.null

services:
    cache.adapter.null:
        class: Symfony\Component\Cache\Adapter\NullAdapter
        arguments: [~] # small trick to avoid arguments errors on compile-time.
Run Code Online (Sandbox Code Playgroud)

由于cache.adapter.null默认情况下服务不可用,您可能需要手动定义它.