How to configure Redis cache for Doctrine in Symfony application

Viewed 17514

In my config_prod.yml file I have following configuration. Where can I configure Redis driver – options like unix socket (or host), database number, etc. ?

doctrine:
    orm:
        metadata_cache_driver: redis
        query_cache_driver: redis
        result_cache_driver: redis
4 Answers

For symfony 4.4/5 here is how it's done, because the docs are a bit confusing.

You need to first set up the cache pool:

#config/packages/cache.yaml

framework:
  cache:
    default_redis_provider: 'redis://localhost' # or '%env(resolve:REDIS_URL)%'

    pools:
      custom_cache_pool:
        adapter: cache.adapter.redis

And then use this pool for the doctrine result cache like so:

#config/packages/doctrine.yaml

doctrine:
  ...
  orm:
    result_cache_driver:
      type: pool
      pool: custom_cache_pool

I've noticed that author asks about redis, not predis, but I found simplest "out-of-box" way for 3.4.*, if you just want a quick start:

doctrine:
    orm:
        default_entity_manager: default
        entity_managers:
            default:
                metadata_cache_driver:
                    type: predis
                    host: '%app.redis.host%'
                    port: '%app.redis.port%'
                    database: 1
                result_cache_driver:
                    cache_provider: doctrine.orm.default_metadata_cache
                query_cache_driver:
                    cache_provider: doctrine.orm.default_metadata_cache

This requires predis client:

$ composer require predis/predis

What happens now? For doctrine metadata cache we have Predis\Client wrapped by built-in Doctrine\Common\Cache\PredisCache. Result and query cache drivers configured as aliases for metadata cache driver (aliases to cache provider, actually), so they all use same database, host and port. If you clear metadata cache by bin/console or call flushdb directly by redis-cli, cache for results and queries also will be erased.

This solution doesn't require any new services.

Related