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:
use Symfony\Contracts\Cache\ItemInterface;
// The callable will only be executed on a cache miss.
$value = $pool->get('my_cache_key', function (ItemInterface $item) {
$item->expiresAfter(3600);
// ... do some HTTP request or heavy computations
$computedValue = 'foobar';
return $computedValue;
});
echo $value; // 'foobar'
// ... and to remove the cache key
$pool->delete('my_cache_key');
Symfony supports Cache Contracts and PSR-6/16 interfaces. You can read more about these at the component documentation.
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 examples 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:
The Cache component comes with a series of adapters pre-configured:
cache.adapter.redis_tag_aware (Redis adapter optimized to work with tags)
Some of these adapters could be configured via shortcuts. Using these shortcuts
will create pools with service IDs that follow the pattern cache.[type].
Creating Custom (Namespaced) Pools
You can also create more customized pools:
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:
use Symfony\Contracts\Cache\CacheInterface;
// from a controller method
public function listProducts(CacheInterface $customThingCache)
{
// ...
}
// in a service
public function __construct(CacheInterface $customThingCache)
{
// ...
}
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:
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.
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.
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_clearercache.system_clearercache.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:
$ php bin/console cache:pool:list
Clear one pool:
$ php bin/console cache:pool:clear my_cache_pool
Clear all custom pools:
$ php bin/console cache:pool:clear cache.app_clearer
Clear all caches everywhere:
$ php bin/console cache:pool:clear cache.global_clearer
Clear cache by tag(s):
New in version 6.1: The cache:pool:invalidate-tags command was introduced in Symfony 6.1.
# invalidate tag1 from all taggable pools
$ php bin/console cache:pool:invalidate-tags tag1
# invalidate tag1 & tag2 from all taggable pools
$ php bin/console cache:pool:invalidate-tags tag1 tag2
# invalidate tag1 & tag2 from cache.app pool
$ php bin/console cache:pool:invalidate-tags tag1 tag2 --pool=cache.app
# invalidate tag1 & tag2 from cache1 & cache2 pools
$ php bin/console cache:pool:invalidate-tags tag1 tag2 -p cache1 -p cache2
Encrypting the Cache
To encrypt the cache using libsodium, you can use the
Symfony\Component\Cache\Marshaller\SodiumMarshaller.
First, you need to generate a secure key and add it to your secret
store as CACHE_DECRYPTION_KEY:
$ php -r 'echo base64_encode(sodium_crypto_box_keypair());'
Then, register the SodiumMarshaller service using this key:
Caution
This will encrypt the values of the cache items, but not the cache keys. Be careful not to leak sensitive data in the keys.
When configuring multiple keys, the first key will be used for reading and
writing, and the additional key(s) will only be used for reading. Once all
cache items encrypted with the old key have expired, you can completely remove
OLD_CACHE_DECRYPTION_KEY.