skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. If you want to change cache pool depending on e.g. environment, than type hinting will not help.

    Bu you can change service definition with defined pool to use:

    # services.yaml
    AppServiceSapListService:
        arguments:
            $cache: '@cache.auth'
    
    # services_local.yaml
    AppServiceSapListService:
        arguments:
            $cache: '@cache.sap'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search