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.

New in version 4.2: The cache contracts were introduced in Symfony 4.2.

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. $container->loadFromExtension('framework', [
    3. 'cache' => [
    4. 'app' => 'cache.adapter.filesystem',
    5. 'system' => 'cache.adapter.system',
    6. ],
    7. ]);

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

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. $container->loadFromExtension('framework', [
    3. 'cache' => [
    4. // Only used with cache.adapter.filesystem
    5. 'directory' => '%kernel.cache_dir%/pools',
    6. // Service: cache.doctrine
    7. 'default_doctrine_provider' => 'app.doctrine_cache',
    8. // Service: cache.psr6
    9. 'default_psr6_provider' => 'app.my_psr6_service',
    10. // Service: cache.redis
    11. 'default_redis_provider' => 'redis://localhost',
    12. // Service: cache.memcached
    13. 'default_memcached_provider' => 'memcached://localhost',
    14. // Service: cache.pdo
    15. 'default_pdo_provider' => 'doctrine.dbal.default_connection',
    16. ],
    17. ]);

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. $container->loadFromExtension('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. ],
    12. // creates a "my_cache_pool" service
    13. // autowireable via "CacheInterface $myCachePool"
    14. 'my_cache_pool' => [
    15. 'adapter' => 'cache.adapter.filesystem',
    16. ],
    17. // uses the default_memcached_provider from above
    18. 'acme.cache' => [
    19. 'adapter' => 'cache.adapter.memcached',
    20. ],
    21. // control adapter's configuration
    22. 'foobar.cache' => [
    23. 'adapter' => 'cache.adapter.memcached',
    24. 'provider' => 'memcached://user:[email protected]',
    25. ],
    26. // uses the "foobar.cache" pool as its backend but controls
    27. // the lifetime and (like all pools) has a separate cache namespace
    28. 'short_cache' => [
    29. 'adapter' => 'foobar.cache',
    30. 'default_lifetime' => 60,
    31. ],
    32. ],
    33. ],
    34. ]);

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. $container->loadFromExtension('framework', [
    4. 'cache' => [
    5. 'pools' => [
    6. 'cache.my_redis' => [
    7. 'adapter' => 'cache.adapter.redis',
    8. 'provider' => 'app.my_custom_redis_provider',
    9. ],
    10. ],
    11. ],
    12. ]);
    13. $container->register('app.my_custom_redis_provider', \Redis::class)
    14. ->setFactory([RedisAdapter::class, 'createConnection'])
    15. ->addArgument('redis://localhost')
    16. ->addArgument([
    17. 'retry_interval' => 2,
    18. 'timeout' => 10
    19. ])
    20. ;

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.

New in version 4.4: Support for configuring a chain using framework.cache.pools was introduced in Symfony 4.4.

  • 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. $container->loadFromExtension('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]'],
    11. ],
    12. ],
    13. ],
    14. ],
    15. ]);

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. $container->loadFromExtension('framework', [
    3. 'cache' => [
    4. 'pools' => [
    5. 'my_cache_pool' => [
    6. 'adapter' => 'cache.adapter.redis',
    7. 'tags' => true,
    8. ],
    9. ],
    10. ],
    11. ]);

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. $container->loadFromExtension('framework', [
    3. 'cache' => [
    4. 'pools' => [
    5. 'my_cache_pool' => [
    6. 'adapter' => 'cache.adapter.redis',
    7. 'tags' => 'tag_pool',
    8. ],
    9. 'tag_pool' => [
    10. 'adapter' => 'cache.adapter.apcu',
    11. ],
    12. ],
    13. ],
    14. ]);

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

New in version 4.3: The cache:pool:list command was introduced in Symfony 4.3.

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

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