如何注入特定的缓存池?

Cal*_*ane 3 php symfony symfony-cache symfony5

在我的 Symfony 5 应用程序中,我想针对不同的任务以及不同的环境使用不同的缓存。

例如我的配置如下所示:

framework:
    cache:
        pools:
            cache.auth:
                adapter: cache.adapter.redis
                provider: app.my_custom_redis_provider
            cache.sap:
                adapter: cache.adapter.redis
                provider: app.my_custom_redis_provider
services:
    app.my_custom_redis_provider:
        arguments:
            - '%env(REDIS_URL)%'
            -
                retry_interval: 2
                timeout: '%env(REDIS_TIMEOUT)%'
        class: Redis
        factory:
            - Symfony\Component\Cache\Adapter\RedisAdapter
            - createConnection
Run Code Online (Sandbox Code Playgroud)

我在我的类中使用依赖注入。那么我如何定义特定类使用这两个缓存池中的哪一个呢?

目前我的缓存是这样的:

class SapListService implements ListServiceInterface
{
    use LoggerTrait;

    private CountryServiceInterface $countryService;
    private CurrencyServiceInterface $currencyService;

    public function __construct(
        SapClientFactoryInterface $sapClient,
        CacheItemPoolInterface $cache,
        ParameterBagInterface $params
    ) {
        $sapUser = $params->get('sap_user');
        $sapPw = $params->get('sap_pw');
        $urlStruktur = $params->get('sap_struktur');
        $this->countryService = $sapClient->getCountryService($sapUser, $sapPw, $urlStruktur, $cache);
        $this->currencyService = $sapClient->getCurrencyService($sapUser, $sapPw, $urlStruktur, $cache);
    } 
Run Code Online (Sandbox Code Playgroud)

如何配置我的SapListService以使用cache.sap池?

yiv*_*ivi 7

文档对此进行了解释。

每个自定义池都成为一个服务,其服务ID 是该池的名称(例如custom_thing.cache)。还使用名称的驼峰式版本为每个池创建自动装配别名 - 例如,可以通过命名参数 $customThingCache 并使用 Symfony\Contracts\Cache\CacheInterface 或 Psr\Cache 对其进行类型提示来自动注入 custom_thing.cache \CacheItemPool接口:

因此,就您而言,您可以输入提示:

Psr\Cache\CacheItemPoolInterface $cacheSap
Run Code Online (Sandbox Code Playgroud)