Symfony Cache reference
8 May 2023 (Updated 8 May 2023)
In a nutshell
Symfony’s Cache component helps you implement caching in your web applications.
This is how you’d typically use the Cache component:
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');
Pools: Group of cache items
A pool is a group of cache items under a namespace. In your code, you’ll use a service to interact with each pool.
For example, you might choose to group your cache items in the following pools:
- Images: For caching files.
- Users: For caching user DB records.
- Secrets: For caching AWS secrets.
Default pools
Two pools are enabled by default:
cache.app
: Used in your application code.cache.system
: Used for things like serializer, annotations, and validations.
These are configured in config/packages/cache.yaml
:
# config/packages/cache.yaml
framework:
cache:
app: cache.adapter.filesystem
system: cache.adapter.system
See all available cache pools
php bin/console cache:pool:list
Clear a pool
php bin/console cache:pool:clear my_cache_pool
Adapters
A cache adapter is a class that implements the AbstractAdapter
interface allowing you to manage your caching using storage systems like Memcached or Redis.
The Cache component offers several pre-configured adapters:
- cache.adapter.apcu
- cache.adapter.array
- cache.adapter.filesystem
- cache.adapter.memcached
- cache.adapter.pdo
- cache.adapter.psr6
- cache.adapter.redis
- cache.adapter.redis_tag_aware (Redis adapter optimized to work with tags)
Sources/links
Tagged:
Symfony
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment