New in Symfony 3.2: Tagged Cache

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Nicolas Grekas
in #19047.
In Symfony 3.1 we added a new Cache component that was a strict implementation of the PSR-6: Caching Interface standard. In Symfony 3.2 we decided to improve the cache with some features not defined by the standard.
The first new feature is the tag-based invalidation to create tagged caches. Imagine that your application is an e-commerce application that stores users' reviews in the cache. When saving those reviews, you can now associate tags to them:
1 2 3 4 5 6 7 8 9
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
$cache = new FilesystemAdapter();
$review = $cache->getItem('reviews-'.$reviewId);
$review->set('...');
$review->tag(['reviews', 'products', 'product-'.$productId]);
$cache->save($review);
The cached review is associated with three different tags that can be used to invalidate related items:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// the HTML structure of reviews has changed:
// invalidate all reviews
$cache->invalidateTags('reviews');
// a special sale is enabled in the store:
// invalidate anything related to products
$cache->invalidateTags('products');
// the data of the product #123 has changed:
// invalidate anything related to that product
$cache->invalidateTags('product-123');
// a major store update is being deployed:
// invalidate all the information related to products and reviews
$cache->invalidateTags(['products', 'reviews']);
// after invalidating any of the previous tags, the item is no longer
// available in the cache:
$cache->getItem('reviews-'.$reviewId)->isHit(); // returns false
The Cache component now defines a TagAwareAdapterInterface
to add tag-based
invalidation to your own cache adapters and TaggedCacheItemInterface
to
allow tagging cache items. In addition, it includes a TagAwareRedisAdapter
to enable tag-based invalidation when using Redis.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
-- Phil Karlton
Thanks for this feature, it should make cache invalidation a little less hard!
I'd achieved something similar in the past with long cache key names and regexp cache cleanup, this is certainly a lot neater and easier to follow!
As from Symfony 3.1 onwards, Apcu will automatically be used if available, assuming possible, would be great if Apcu adapter can be made tag aware.
Regarding our question which tag aware adapters: Is or will there be something for Varnish?