Cache

Cache

Using a cache is a great way of making your application run quicker. The Symfony cache component ships with many adapters to different storages. Every adapter is developed for high performance.

The following example shows a typical usage of the cache:

  1. use Symfony\Contracts\Cache\ItemInterface;
  2. // The callable will only be executed on a cache miss.
  3. $value = $pool->get('my_cache_key', function (ItemInterface $item) {
  4. $item->expiresAfter(3600);
  5. // ... do some HTTP request or heavy computations
  6. $computedValue = 'foobar';
  7. return $computedValue;
  8. });
  9. echo $value; // 'foobar'
  10. // ... and to remove the cache key
  11. $pool->delete('my_cache_key');

Symfony supports Cache Contracts, PSR-6/16 and Doctrine Cache interfaces. You can read more about these at the component documentation.

Configuring Cache with FrameworkBundle

When configuring the cache component there are a few concepts you should know of:

Pool

This is a service that you will interact with. Each pool will always have its own namespace and cache items. There is never a conflict between pools.

Adapter

An adapter is a template that you use to create pools.

Provider

A provider is a service that some adapters use to connect to the storage. Redis and Memcached are example of such adapters. If a DSN is used as the provider then a service is automatically created.

There are two pools that are always enabled by default. They are cache.app and cache.system. The system cache is used for things like annotations, serializer, and validation. The cache.app can be used in your code. You can configure which adapter (template) they use by using the app and system key like:

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. app: cache.adapter.filesystem
    5. system: cache.adapter.system
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:cache app="cache.adapter.filesystem"
    12. system="cache.adapter.system"
    13. />
    14. </framework:config>
    15. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->cache()
    5. ->app('cache.adapter.filesystem')
    6. ->system('cache.adapter.system')
    7. ;
    8. };

The Cache component comes with a series of adapters pre-configured:

New in version 5.2: cache.adapter.redis_tag_aware has been introduced in Symfony 5.2.

Some of these adapters could be configured via shortcuts. Using these shortcuts will create pools with service IDs that follow the pattern cache.[type].

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. directory: '%kernel.cache_dir%/pools' # Only used with cache.adapter.filesystem
    5. # service: cache.doctrine
    6. default_doctrine_provider: 'app.doctrine_cache'
    7. # service: cache.psr6
    8. default_psr6_provider: 'app.my_psr6_service'
    9. # service: cache.redis
    10. default_redis_provider: 'redis://localhost'
    11. # service: cache.memcached
    12. default_memcached_provider: 'memcached://localhost'
    13. # service: cache.pdo
    14. default_pdo_provider: 'doctrine.dbal.default_connection'
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <!--
    12. default_doctrine_provider: Service: cache.doctrine
    13. default_psr6_provider: Service: cache.psr6
    14. default_redis_provider: Service: cache.redis
    15. default_memcached_provider: Service: cache.memcached
    16. default_pdo_provider: Service: cache.pdo
    17. -->
    18. <!-- "directory" attribute is only used with cache.adapter.filesystem -->
    19. <framework:cache directory="%kernel.cache_dir%/pools"
    20. default_doctrine_provider="app.doctrine_cache"
    21. default_psr6_provider="app.my_psr6_service"
    22. default_redis_provider="redis://localhost"
    23. default_memcached_provider="memcached://localhost"
    24. default_pdo_provider="doctrine.dbal.default_connection"
    25. />
    26. </framework:config>
    27. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->cache()
    5. // Only used with cache.adapter.filesystem
    6. ->directory('%kernel.cache_dir%/pools')
    7. // Service: cache.doctrine
    8. ->defaultDoctrineProvider('app.doctrine_cache')
    9. // Service: cache.psr6
    10. ->defaultPsr6Provider('app.my_psr6_service')
    11. // Service: cache.redis
    12. ->defaultRedisProvider('redis://localhost')
    13. // Service: cache.memcached
    14. ->defaultMemcachedProvider('memcached://localhost')
    15. // Service: cache.pdo
    16. ->defaultPdoProvider('doctrine.dbal.default_connection')
    17. ;
    18. };

Creating Custom (Namespaced) Pools

You can also create more customized pools:

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. default_memcached_provider: 'memcached://localhost'
    5. pools:
    6. # creates a "custom_thing.cache" service
    7. # autowireable via "CacheInterface $customThingCache"
    8. # uses the "app" cache configuration
    9. custom_thing.cache:
    10. adapter: cache.app
    11. # creates a "my_cache_pool" service
    12. # autowireable via "CacheInterface $myCachePool"
    13. my_cache_pool:
    14. adapter: cache.adapter.filesystem
    15. # uses the default_memcached_provider from above
    16. acme.cache:
    17. adapter: cache.adapter.memcached
    18. # control adapter's configuration
    19. foobar.cache:
    20. adapter: cache.adapter.memcached
    21. provider: 'memcached://user:[email protected]'
    22. # uses the "foobar.cache" pool as its backend but controls
    23. # the lifetime and (like all pools) has a separate cache namespace
    24. short_cache:
    25. adapter: foobar.cache
    26. default_lifetime: 60
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:cache default-memcached-provider="memcached://localhost">
    12. <!-- creates a "custom_thing.cache" service
    13. autowireable via "CacheInterface $customThingCache"
    14. uses the "app" cache configuration -->
    15. <framework:pool name="custom_thing.cache" adapter="cache.app"/>
    16. <!-- creates a "my_cache_pool" service
    17. autowireable via "CacheInterface $myCachePool" -->
    18. <framework:pool name="my_cache_pool" adapter="cache.adapter.filesystem"/>
    19. <!-- uses the default_memcached_provider from above -->
    20. <framework:pool name="acme.cache" adapter="cache.adapter.memcached"/>
    21. <!-- control adapter's configuration -->
    22. <framework:pool name="foobar.cache" adapter="cache.adapter.memcached"
    23. provider="memcached://user:[email protected]"
    24. />
    25. <!-- uses the "foobar.cache" pool as its backend but controls
    26. the lifetime and (like all pools) has a separate cache namespace -->
    27. <framework:pool name="short_cache" adapter="foobar.cache" default-lifetime="60"/>
    28. </framework:cache>
    29. </framework:config>
    30. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $cache = $framework->cache();
    5. $cache->defaultMemcachedProvider('memcached://localhost');
    6. // creates a "custom_thing.cache" service
    7. // autowireable via "CacheInterface $customThingCache"
    8. // uses the "app" cache configuration
    9. $cache->pool('custom_thing.cache')
    10. ->adapters(['cache.app']);
    11. // creates a "my_cache_pool" service
    12. // autowireable via "CacheInterface $myCachePool"
    13. $cache->pool('my_cache_pool')
    14. ->adapters(['cache.adapter.filesystem']);
    15. // uses the default_memcached_provider from above
    16. $cache->pool('acme.cache')
    17. ->adapters(['cache.adapter.memcached']);
    18. // control adapter's configuration
    19. $cache->pool('foobar.cache')
    20. ->adapters(['cache.adapter.memcached'])
    21. ->provider('memcached://user:[email protected]');
    22. $cache->pool('short_cache')
    23. ->adapters(['foobar.cache'])
    24. ->defaultLifetime(60);
    25. };

Each pool manages a set of independent cache keys: keys from different pools never collide, even if they share the same backend. This is achieved by prefixing keys with a namespace that’s generated by hashing the name of the pool, the name of the cache adapter class and a configurable seed that defaults to the project directory and compiled container class.

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 Symfony\Contracts\Cache\CacheInterface or Psr\Cache\CacheItemPoolInterface:

  1. use Symfony\Contracts\Cache\CacheInterface;
  2. // from a controller method
  3. public function listProducts(CacheInterface $customThingCache)
  4. {
  5. // ...
  6. }
  7. // in a service
  8. public function __construct(CacheInterface $customThingCache)
  9. {
  10. // ...
  11. }

Tip

If you need the namespace to be interoperable with a third-party app, you can take control over auto-generation by setting the namespace attribute of the cache.pool service tag. For example, you can override the service definition of the adapter:

  • YAML

    1. # config/services.yaml
    2. services:
    3. app.cache.adapter.redis:
    4. parent: 'cache.adapter.redis'
    5. tags:
    6. - { name: 'cache.pool', namespace: 'my_custom_namespace' }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="app.cache.adapter.redis" parent="cache.adapter.redis">
    9. <tag name="cache.pool" namespace="my_custom_namespace"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. $services->set('app.cace.adapter.redis')
    6. ->parent('cache.adapter.redis')
    7. ->tag('cache.pool', ['namespace' => 'my_custom_namespace']);
    8. };

Custom Provider Options

Some providers have specific options that can be configured. The RedisAdapter allows you to create providers with the options timeout, retry_interval. etc. To use these options with non-default values you need to create your own \Redis provider and use that when configuring the pool.

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. pools:
    5. cache.my_redis:
    6. adapter: cache.adapter.redis
    7. provider: app.my_custom_redis_provider
    8. services:
    9. app.my_custom_redis_provider:
    10. class: \Redis
    11. factory: ['Symfony\Component\Cache\Adapter\RedisAdapter', 'createConnection']
    12. arguments:
    13. - 'redis://localhost'
    14. - { retry_interval: 2, timeout: 10 }
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:cache>
    12. <framework:pool name="cache.my_redis" adapter="cache.adapter.redis" provider="app.my_custom_redis_provider"/>
    13. </framework:cache>
    14. </framework:config>
    15. <services>
    16. <service id="app.my_custom_redis_provider" class="\Redis">
    17. <factory class="Symfony\Component\Cache\Adapter\RedisAdapter" method="createConnection"/>
    18. <argument>redis://localhost</argument>
    19. <argument type="collection">
    20. <argument key="retry_interval">2</argument>
    21. <argument key="timeout">10</argument>
    22. </argument>
    23. </service>
    24. </services>
    25. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Component\Cache\Adapter\RedisAdapter;
    3. use Symfony\Component\DependencyInjection\ContainerBuilder;
    4. use Symfony\Config\FrameworkConfig;
    5. return static function (ContainerBuilder $container, FrameworkConfig $framework) {
    6. $framework->cache()
    7. ->pool('cache.my_redis')
    8. ->adapters(['cache.adapter.redis'])
    9. ->provider('app.my_custom_redis_provider');
    10. $container->register('app.my_custom_redis_provider', \Redis::class)
    11. ->setFactory([RedisAdapter::class, 'createConnection'])
    12. ->addArgument('redis://localhost')
    13. ->addArgument([
    14. 'retry_interval' => 2,
    15. 'timeout' => 10
    16. ])
    17. ;
    18. };

Creating a Cache Chain

Different cache adapters have different strengths and weaknesses. Some might be really quick but optimized to store small items and some may be able to contain a lot of data but are quite slow. To get the best of both worlds you may use a chain of adapters.

A cache chain combines several cache pools into a single one. When storing an item in a cache chain, Symfony stores it in all pools sequentially. When retrieving an item, Symfony tries to get it from the first pool. If it’s not found, it tries the next pools until the item is found or an exception is thrown. Because of this behavior, it’s recommended to define the adapters in the chain in order from fastest to slowest.

If an error happens when storing an item in a pool, Symfony stores it in the other pools and no exception is thrown. Later, when the item is retrieved, Symfony stores the item automatically in all the missing pools.

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. pools:
    5. my_cache_pool:
    6. default_lifetime: 31536000 # One year
    7. adapters:
    8. - cache.adapter.array
    9. - cache.adapter.apcu
    10. - {name: cache.adapter.redis, provider: 'redis://user:[email protected]'}
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <framework:config>
    9. <framework:cache>
    10. <framework:pool name="my_cache_pool" default-lifetime="31536000">
    11. <framework:adapter name="cache.adapter.array"/>
    12. <framework:adapter name="cache.adapter.apcu"/>
    13. <framework:adapter name="cache.adapter.redis" provider="redis://user:[email protected]"/>
    14. </framework:pool>
    15. </framework:cache>
    16. </framework:config>
    17. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->cache()
    5. ->pool('my_cache_pool')
    6. ->defaultLifetime(31536000) // One year
    7. ->adapters([
    8. 'cache.adapter.array',
    9. 'cache.adapter.apcu',
    10. ['name' => 'cache.adapter.redis', 'provider' => 'redis://user:[email protected]'],
    11. ])
    12. ;
    13. };

Using Cache Tags

In applications with many cache keys it could be useful to organize the data stored to be able to invalidate the cache more efficiently. One way to achieve that is to use cache tags. One or more tags could be added to the cache item. All items with the same key could be invalidated with one function call:

  1. use Symfony\Contracts\Cache\ItemInterface;
  2. use Symfony\Contracts\Cache\TagAwareCacheInterface;
  3. class SomeClass
  4. {
  5. private $myCachePool;
  6. // using autowiring to inject the cache pool
  7. public function __construct(TagAwareCacheInterface $myCachePool)
  8. {
  9. $this->myCachePool = $myCachePool;
  10. }
  11. public function someMethod()
  12. {
  13. $value0 = $this->myCachePool->get('item_0', function (ItemInterface $item) {
  14. $item->tag(['foo', 'bar']);
  15. return 'debug';
  16. });
  17. $value1 = $this->myCachePool->get('item_1', function (ItemInterface $item) {
  18. $item->tag('foo');
  19. return 'debug';
  20. });
  21. // Remove all cache keys tagged with "bar"
  22. $this->myCachePool->invalidateTags(['bar']);
  23. }
  24. }

The cache adapter needs to implement Symfony\Contracts\Cache\TagAwareCacheInterface to enable this feature. This could be added by using the following configuration.

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. pools:
    5. my_cache_pool:
    6. adapter: cache.adapter.redis
    7. tags: true
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:cache>
    12. <framework:pool name="my_cache_pool" adapter="cache.adapter.redis" tags="true"/>
    13. </framework:cache>
    14. </framework:config>
    15. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->cache()
    5. ->pool('my_cache_pool')
    6. ->tags(true)
    7. ->adapters(['cache.adapter.redis'])
    8. ;
    9. };

Tags are stored in the same pool by default. This is good in most scenarios. But sometimes it might be better to store the tags in a different pool. That could be achieved by specifying the adapter.

  • YAML

    1. # config/packages/cache.yaml
    2. framework:
    3. cache:
    4. pools:
    5. my_cache_pool:
    6. adapter: cache.adapter.redis
    7. tags: tag_pool
    8. tag_pool:
    9. adapter: cache.adapter.apcu
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <framework:config>
    9. <framework:cache>
    10. <framework:pool name="my_cache_pool" adapter="cache.adapter.redis" tags="tag_pool"/>
    11. <framework:pool name="tag_pool" adapter="cache.adapter.apcu"/>
    12. </framework:cache>
    13. </framework:config>
    14. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->cache()
    5. ->pool('my_cache_pool')
    6. ->tags('tag_pool')
    7. ->adapters(['cache.adapter.redis'])
    8. ;
    9. $framework->cache()
    10. ->pool('tag_pool')
    11. ->adapters(['cache.adapter.apcu'])
    12. ;
    13. };

Note

The interface Symfony\Contracts\Cache\TagAwareCacheInterface is autowired to the cache.app service.

Clearing the Cache

To clear the cache you can use the bin/console cache:pool:clear [pool] command. That will remove all the entries from your storage and you will have to recalculate all the values. You can also group your pools into “cache clearers”. There are 3 cache clearers by default:

  • cache.global_clearer
  • cache.system_clearer
  • cache.app_clearer

The global clearer clears all the cache items in every pool. The system cache clearer is used in the bin/console cache:clear command. The app clearer is the default clearer.

To see all available cache pools:

  1. $ php bin/console cache:pool:list

Clear one pool:

  1. $ php bin/console cache:pool:clear my_cache_pool

Clear all custom pools:

  1. $ php bin/console cache:pool:clear cache.app_clearer

Clear all caches everywhere:

  1. $ php bin/console cache:pool:clear cache.global_clearer

Encrypting the Cache

New in version 5.1: The Symfony\Component\Cache\Marshaller\SodiumMarshaller class was introduced in Symfony 5.1.

To encrypt the cache using libsodium, you can use the Symfony\Component\Cache\Marshaller\SodiumMarshaller.

First, you need to generate a secure key and add it to your secret store as CACHE_DECRYPTION_KEY:

  1. $ php -r 'echo base64_encode(sodium_crypto_box_keypair());'

Then, register the SodiumMarshaller service using this key:

  • YAML

    1. # config/packages/cache.yaml
    2. # ...
    3. services:
    4. Symfony\Component\Cache\Marshaller\SodiumMarshaller:
    5. decorates: cache.default_marshaller
    6. arguments:
    7. - ['%env(base64:CACHE_DECRYPTION_KEY)%']
    8. # use multiple keys in order to rotate them
    9. #- ['%env(base64:CACHE_DECRYPTION_KEY)%', '%env(base64:OLD_CACHE_DECRYPTION_KEY)%']
    10. - '@Symfony\Component\Cache\Marshaller\SodiumMarshaller.inner'
  • XML

    1. <!-- config/packages/cache.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <!-- ... -->
    11. <services>
    12. <service id="Symfony\Component\Cache\Marshaller\SodiumMarshaller" decorates="cache.default_marshaller">
    13. <argument type="collection">
    14. <argument>env(base64:CACHE_DECRYPTION_KEY)</argument>
    15. <!-- use multiple keys in order to rotate them -->
    16. <!-- <argument>env(base64:OLD_CACHE_DECRYPTION_KEY)</argument> -->
    17. </argument>
    18. <argument type="service" id="Symfony\Component\Cache\Marshaller\SodiumMarshaller.inner"/>
    19. </service>
    20. </services>
    21. </container>
  • PHP

    1. // config/packages/cache.php
    2. use Symfony\Component\Cache\Marshaller\SodiumMarshaller;
    3. use Symfony\Component\DependencyInjection\ChildDefinition;
    4. use Symfony\Component\DependencyInjection\Reference;
    5. // ...
    6. $container->setDefinition(SodiumMarshaller::class, new ChildDefinition('cache.default_marshaller'))
    7. ->addArgument(['env(base64:CACHE_DECRYPTION_KEY)'])
    8. // use multiple keys in order to rotate them
    9. //->addArgument(['env(base64:CACHE_DECRYPTION_KEY)', 'env(base64:OLD_CACHE_DECRYPTION_KEY)'])
    10. ->addArgument(new Reference(SodiumMarshaller::class.'.inner'));

Caution

This will encrypt the values of the cache items, but not the cache keys. Be careful not the leak sensitive data in the keys.

When configuring multiple keys, the first key will be used for reading and writing, and the additional key(s) will only be used for reading. Once all cache items encrypted with the old key have expired, you can remove OLD_CACHE_DECRYPTION_KEY completely.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.