Install via Composer (Symfony Flex auto-configures):
composer require phpfastcache/phpfastcache-bundle
AppKernel registration needed (Flex handles it).Configure Cache Driver (.env):
# Example: Filesystem driver (default)
CACHE_DRIVER=filesystem
CACHE_PATH=%kernel.project_dir%/var/cache
# Alternative: APCu, Redis, Memcached, etc.
CACHE_DRIVER=apcu
First Use Case: Cache a Controller Response
Inject the PhpFastCache service into a controller:
use PhpFastCache\PhpFastCache;
use Symfony\Component\HttpFoundation\Response;
class HomeController extends AbstractController
{
public function index(PhpFastCache $cache): Response
{
$cacheKey = 'homepage_content';
$content = $cache->getItem($cacheKey);
if (!$content->isHit()) {
$content->set(expiresAfter(3600)); // 1 hour TTL
$content->set('Hello, cached world!');
$cache->save($content);
}
return new Response($content->get());
}
}
Verify Installation
php bin/console cache:clear to test cache operations.// Cache with 5-minute TTL
$item = $cache->getItem('user_123_data');
if (!$item->isHit()) {
$item->set(expiresAfter(300)); // 5 minutes
$item->set($this->fetchUserData(123));
$cache->save($item);
}
return $item->get();
// Cache with tags (e.g., 'users', 'premium')
$item = $cache->getItem('user_123_profile');
$item->setTags(['users', 'premium']);
$item->set(expiresAfter(3600));
$cache->save($item);
// Invalidate all 'users' tagged items
$cache->invalidateTags(['users']);
config/packages/twig.yaml:
twig:
cache: true
cache_prefix: '%kernel.cache_dir%/twig'
cache tag in templates:
{% cache app.homepage (request.uri) %}
{{ render(controller('AppController:homepage')) }}
{% endcache %}
PhpFastCache service (recommended):
public function __construct(private PhpFastCache $cache) {}
# config/services.yaml
services:
App\Cache\CustomPool:
arguments:
- '@phpfastcache.cache.pool' # Base pool
- 'custom_pool' # Unique pool name
cache.invalidate events (e.g., after user updates):
use Symfony\Component\EventDispatcher\GenericEvent;
public function onUserUpdate(GenericEvent $event): void
{
$this->cache->invalidateTags(['users']);
}
get() with a fallback:
$data = $cache->get('expensive_query', function() {
return $this->db->query('SELECT * FROM large_table');
});
Driver Compatibility
apcu.enable_cli=1 in php.ini for CLI cache operations.php-redis, php-memcached) is installed.CACHE_PATH (e.g., chmod -R 775 var/cache).Tag Invalidation Quirks
['Users'] vs ['users']).invalidateAll() for a full reset.TTL Precision
expiresAfter(1) may expire after 1.1 seconds).expiresAt() with new \DateTime('+1 second').Symfony Profiler Overhead
# config/packages/dev/profiler.yaml
profiler: false
Serialization Issues
serialize()/unserialize() for custom objects:
$item->set(serialize($unserializableObject));
return unserialize($item->get());
Check Cache Contents
$items = $cache->getPool()->getItems();
dd($items);
Enable Verbose Logging
# config/packages/monolog.yaml
handlers:
cache:
type: stream
path: "%kernel.logs_dir%/cache.log"
channels: ["cache"]
$this->logger->info('Cache miss', ['key' => $key, 'pool' => $cache->getPool()->getName()]);
Clear Stale Cache
php bin/console cache:pool:clear phpfastcache.cache.pool
Custom Cache Item Class
PhpFastCache\CacheItem to add metadata:
class ExtendedCacheItem extends CacheItem {
private $requestId;
public function setRequestId(string $id): self {
$this->requestId = $id;
return $this;
}
}
services.yaml:
services:
App\Cache\ExtendedCacheItem:
tags: ['phpfastcache.cache_item']
Dynamic Pool Configuration
# config/packages/prod/phpfastcache.yaml
phpfastcache:
pools:
default:
adapter: apcu
prefix: 'prod_'
default_ttl: 86400 # 1 day
Cache Warmer
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
class CacheWarmer implements CacheWarmerInterface {
public function warmUp($cacheDir): void {
$cache = $this->container->get('phpfastcache.cache.pool');
$cache->save($cache->getItem('homepage')->set('preloaded'));
}
}
services.yaml:
services:
App\Cache\CacheWarmer:
tags: [kernel.cache_warmer]
PSR-6 Compatibility
phpfastcache library directly for PSR-6 compliance:
use PhpFastCache\CacheManager;
use PhpFastCache\Cache\CacheInterface;
$cacheManager = new CacheManager();
$cache = $cacheManager->getInstance('apcu');
$item = $cache->getItem('psr6_key');
How can I help you explore Laravel packages today?