在Symfony 3.1中我们添加了一个全新的cache组件,它是PSR-6: Caching Interface 标准的一个严格实现。在Symfony 3.2中我们决定通过一些没有定义在该标准中的功能来继续改善缓存功能。

第一个新功能是tag-based invalidation (基于标签的失效),用于创建标签化缓存。假设你的程序是一个电商平台,把用户的评论存在缓存中。当存储这些评论时,现在你可以对它们关联一些标签:

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);

缓存了的评论,被关联到三个不同的标签,标签可以用于使相关的个体(评论)失效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// the HTML structure of reviews has changed:
// invalidate all reviews
// 商品评价的HTML结构改变,全部评论失效:
$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
// id为123的产品,其数据发生改变,令其所有关联信息失效:
$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:
// 在无效化前述任何一个标签时,相关item在缓存系统中将不再可用:
$cache->getItem('reviews-'.$reviewId)->isHit();  // returns false

缓存组件现在定义了一个TagAwareAdapterInterface用于把tag-based invalidation(基于标签的失效)添加到你的缓存适配器(cache adapters)中,而TaggedCacheItemInterface则用来对缓存元素(cache items)打标签。除此之外,组件中还包括一个TagAwareRedisAdapter,当使用Redis时它被用来开启基于标签的失效。