Symfony Cache
GitHub Overview
symfony/cache
Provides extended PSR-6, PSR-16 (and tags) implementations
Repository:https://github.com/symfony/cache
Homepage:https://symfony.com/cache
Stars4,156
Watchers10
Forks62
Created:January 19, 2016
Language:PHP
License:MIT License
Topics
cachingcomponentphppsr6symfonysymfony-component
Star History
Data as of: 10/22/2025, 10:04 AM
Cache Library
Symfony Cache
Overview
Symfony Cache is a feature-rich caching component for PHP. It provides PSR-6 and PSR-16 standard compliance, tag-based caching, adapter chaining, and support for various backends, delivering flexible and efficient caching solutions.
Details
The Symfony Cache Component is a comprehensive caching library designed to improve PHP application performance. It provides extended implementations of PSR-6 (Cache Interface) and PSR-16 (Simple Cache) standards, supporting tag-based invalidation and combinations of multiple cache adapters.
Key Technical Features
- PSR-6/PSR-16 Compliance: Interoperability with other libraries through standard interfaces
- Tag-based Caching: Group invalidation of related cache entries
- Adapter Chaining: Hierarchical caching by combining multiple cache layers
- Early Expiration Protection: Probabilistic early expiration to prevent cache stampede
- Marshalling: Optimized serialization with igbinary
- Various Backends: Redis, Memcached, APCu, filesystem, and more
Supported Adapters
- ArrayAdapter: In-memory cache (for testing and development)
- ApcuAdapter: High-speed memory cache using APCu
- RedisAdapter: Redis server support with tag-aware version available
- MemcachedAdapter: Memcached server integration
- FilesystemAdapter: Filesystem-based persistent cache
- PdoAdapter: Database-based cache storage
- ChainAdapter: Combination of multiple adapters
Pros and Cons
Pros
- Standards Compliance: Interoperability and portability through PSR-6/PSR-16
- Flexible Configuration: Optimization through various adapters and configuration options
- Advanced Features: Tag-based invalidation and hierarchical caching via adapter chains
- Performance: Optimized marshalling and early expiration protection
- Symfony Integration: Deep integration with Symfony framework and DI support
- Maintainability: Clear interfaces and comprehensive documentation
Cons
- Complexity: Configuration and understanding can become complex with advanced features
- Symfony Dependency: Full feature utilization is recommended with Symfony framework
- Memory Usage: Memory overhead when using multiple adapters
- Configuration Cost: Experience required for optimal adapter selection in production
Reference Links
Code Examples
Basic Cache Operations
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;
// Initialize cache adapter
$cache = new FilesystemAdapter();
// Get/set cache value using callable
$value = $cache->get('expensive_operation', function (ItemInterface $item): string {
$item->expiresAfter(3600); // 1 hour expiration
// Heavy processing (DB queries, API calls, etc.)
$computedValue = performExpensiveOperation();
return $computedValue;
});
echo $value; // Cached value or callable result
// Delete cache
$cache->delete('expensive_operation');
Redis Adapter and Configuration
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
// Create Redis connection
$redis = RedisAdapter::createConnection('redis://localhost:6379');
// Marshaller with igbinary (performance improvement)
$marshaller = new DefaultMarshaller(true); // Enable igbinary
$cache = new RedisAdapter(
$redis,
'app_cache', // Namespace
3600, // Default TTL
$marshaller // Custom marshaller
);
// Use cache pool with sub-namespace
$userCache = $cache->withSubNamespace('users');
$user = $userCache->get("user_{$userId}", function (ItemInterface $item) use ($userId) {
$item->expiresAfter(1800); // 30 minutes
return fetchUserFromDatabase($userId);
});
Tag-based Cache
use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
// Tag-aware Redis adapter
$client = RedisAdapter::createConnection('redis://localhost');
$cache = new RedisTagAwareAdapter($client);
// Create tagged cache item
$cache->get('user_profile_123', function (ItemInterface $item): array {
$item->expiresAfter(3600);
$item->tag(['user_data', 'profile', 'user_123']);
return [
'id' => 123,
'name' => 'John Doe',
'email' => '[email protected]'
];
});
// Batch invalidation by tags
$cache->invalidateTags(['user_data']); // Invalidate all user_data tagged items
Multi-tier Cache with Adapter Chain
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
// Fast memory (APCu) → Distributed cache (Redis) chain
$cache = new ChainAdapter([
new ApcuAdapter('fast_cache', 300), // 5-minute short-term cache
new RedisAdapter($redis, 'main_cache', 3600) // 1-hour long-term cache
]);
// Use chain cache (search from top tier, save to lower tiers)
$data = $cache->get('complex_calculation', function (ItemInterface $item) {
$item->expiresAfter(1800);
return performComplexCalculation();
});
Symfony Framework Configuration
# config/packages/cache.yaml
framework:
cache:
# Default provider settings
default_redis_provider: 'redis://localhost:6379'
default_memcached_provider: 'memcached://localhost:11211'
pools:
# Fast cache pool
cache.fast:
adapter: cache.adapter.apcu
default_lifetime: 300
# Distributed cache pool
cache.distributed:
adapter: cache.adapter.redis
default_lifetime: 3600
tags: true # Enable tag functionality
# Chain cache pool
cache.multi_tier:
adapters:
- cache.adapter.array
- cache.adapter.apcu
- cache.adapter.redis
default_lifetime: 1800
Custom Cache Pool Injection
// src/Service/UserService.php
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class UserService
{
public function __construct(
private CacheInterface $userCache // cache.user pool is injected
) {}
public function getUserProfile(int $userId): array
{
return $this->userCache->get("profile_{$userId}", function (ItemInterface $item) use ($userId) {
$item->expiresAfter(1800); // 30 minutes
// Actual data retrieval process
return $this->fetchUserFromDatabase($userId);
});
}
public function invalidateUserCache(int $userId): void
{
$this->userCache->delete("profile_{$userId}");
}
}
Versioning and Cache Invalidation
// Version-based cache management
class ProductService
{
private CacheInterface $cache;
public function getProductData(int $productId, string $version = 'v1'): array
{
// Use version-specific namespace
$versionedCache = $this->cache->withSubNamespace("products_{$version}");
return $versionedCache->get("product_{$productId}", function (ItemInterface $item) use ($productId) {
$item->expiresAfter(7200); // 2 hours
return $this->fetchProductFromAPI($productId);
});
}
public function invalidateProductVersion(string $version): void
{
// Clear all cache for specific version
$versionedCache = $this->cache->withSubNamespace("products_{$version}");
$versionedCache->clear();
}
}