Skip to content
Advertisement

How to inject a specific cache pool?

In my Symfony 5 application I want to use different caches for different tasks and of course for different environments.

e.g. my configuration looks like this:

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:
            - SymfonyComponentCacheAdapterRedisAdapter
            - createConnection

I use dependency injection with my classes. So how would I define which of those two cache pools is used by a specific class?

At the moment I get my cache like this:

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);
    } 

How do I configure my SapListService to use the cache.sap pool?

Advertisement

Answer

This is explained on the docs.

Each custom pool becomes a service whose service ID is the name of the pool (e.g. custom_thing.cache). An autowiring alias is also created for each pool using the camel case version of its name – e.g. custom_thing.cache can be injected automatically by naming the argument $customThingCache and type-hinting it with either SymfonyContractsCacheCacheInterface or PsrCacheCacheItemPoolInterface:

So in your case, you’d be able to type-hint for:

PsrCacheCacheItemPoolInterface $cacheSap
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement