diff --git a/cache.rst b/cache.rst index 830988891ea..b17618e1261 100644 --- a/cache.rst +++ b/cache.rst @@ -354,7 +354,7 @@ case the value needs to be recalculated. https://symfony.com/schema/dic/services/services-1.0.xsd"> - + @@ -403,6 +403,135 @@ case the value needs to be recalculated. adapter in the ``app.my_cache_chain_adapter`` +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 efficient. 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 invalidate with one function call:: + + use Symfony\Contracts\Cache\ItemInterface; + + $value0 = $pool->get('item_0', function (ItemInterface $item) { + $item->tag(['foo', 'bar']) + + return 'debug'; + }); + + $value1 = $pool->get('item_1', function (ItemInterface $item) { + $item->tag('foo') + + return 'debug'; + }); + + // Remove all cache keys tagged with "bar" + $pool->invalidateTags(['bar']); + +The cache adapter needs to implement :class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface`` +to enable this feature. This could be added by using the following configuration. + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/cache.yaml + framework: + cache: + pools: + my_cache_pool: + adapter: cache.adapter.redis + tags: true + + .. code-block:: xml + + + + + + + + + + + + + .. code-block:: php + + // config/packages/cache.php + $container->loadFromExtension('framework', [ + 'cache' => [ + 'pools' => [ + 'my_cache_pool' => [ + 'adapter' => 'cache.adapter.redis', + 'tags' => true, + ], + ], + ], + ]); + +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. + +.. configuration-block:: + + .. code-block:: yaml + + # config/packages/cache.yaml + framework: + cache: + pools: + my_cache_pool: + adapter: cache.adapter.redis + tags: tag_pool + tag_pool: + adapter: cache.adapter.apcu + + .. code-block:: xml + + + + + + + + + + + + + + .. code-block:: php + + // config/packages/cache.php + $container->loadFromExtension('framework', [ + 'cache' => [ + 'pools' => [ + 'my_cache_pool' => [ + 'adapter' => 'cache.adapter.redis', + 'tags' => 'tag_pool', + ], + 'tag_pool' => [ + 'adapter' => 'cache.adapter.apcu', + ], + ], + ], + ]); + +.. note:: + + The interface :class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface`` is + autowired to the ``cache.app`` service. + Clearing the Cache ------------------