Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.
Read the updated version of this page for Symfony 6.0 (the current stable version).
Table of Contents
Cache invalidation is the process of removing all cached items related to a change in the state of your model. The most basic kind of invalidation is direct items deletion. But when the state of a primary resource has spread across several cached items, keeping them in sync can be difficult.
The Symfony Cache component provides two mechanisms to help solving this problem:
- Tags based invalidation for managing data dependencies;
- Expiration based invalidation for time related dependencies.
New in version 3.2
Tags based invalidation was introduced in Symfony 3.2.
To benefit from tags based invalidation, you need to attach the proper tags to each cached item. Each tag is a plain string identifier that you can use at any time to trigger the removal of all items associated with this tag.
To attach tags to cached items, you need to use the tag() method that is implemented by cache items, as returned by cache adapters:
1 2 3 4 5 6
$item = $cache->getItem('cache_key'); // ... // add one or more tags $item->tag('tag_1'); $item->tag(array('tag_2', 'tag_3')); $cache->save($item);
1 2 3 4 5
// invalidate all items related to `tag_1` or `tag_3` $cache->invalidateTags(array('tag_1', 'tag_3')); // if you know the cache key, you can also delete the item directly $cache->deleteItem('cache_key');
Using tags invalidation is very useful when tracking cache keys becomes difficult.
The TagAwareAdapter class implements
instantaneous invalidation (time complexity is
N is the number
of invalidated tags). It needs one or two cache adapters: the first required
one is used to store cached items; the second optional one is used to store tags
and their invalidation version number (conceptually similar to their latest
invalidation date). When only one adapter is used, items and tags are all stored
in the same place. By using two adapters, you can e.g. store some big cached items
on the filesystem or in the database and keep tags in a Redis database to sync all
your fronts and have very fast invalidation checks:
1 2 3 4 5 6 7 8 9 10
use Symfony\Component\Cache\Adapter\TagAwareAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; $cache = new TagAwareAdapter( // Adapter for cached items new FilesystemAdapter(), // Adapter for tags new RedisAdapter('redis://localhost') );