Installation:
composer require bigyouth/page-cache-bundle
Add to AppKernel.php:
new BigYouth\PageCacheBundle\BigYouthPageCacheBundle(),
Configure Cache:
Edit app/config/config.yml:
big_youth_page_cache:
enabled: true
cache_dir: "%kernel.cache_dir%/page_cache"
ttl: 3600 # Default: 1 hour
debug: false
First Use Case:
Cache a route by adding the Cache annotation to a controller method:
use BigYouth\PageCacheBundle\Annotation\Cache;
class MyController extends Controller
{
/**
* @Cache()
*/
public function indexAction()
{
return $this->render('my_template.html.twig');
}
}
Route-Based Caching:
Use the @Cache annotation on controller methods or classes to cache entire routes:
/**
* @Cache(ttl=600) // Custom TTL (in seconds)
*/
public function productsAction()
{
// Expensive logic here
}
Dynamic Cache Keys: Override cache keys for dynamic content:
/**
* @Cache(key="products_{page}")
*/
public function productsAction($page = 1)
{
// Cache key includes 'page' parameter
}
Excluding Routes:
Disable caching for specific routes via config.yml:
big_youth_page_cache:
exclude_paths:
- ^/admin
- ^/api
Cache Invalidation: Manually clear cache for a route:
$this->get('big_youth_page_cache.cache')->invalidate('route_name');
Cache component for storage (default).debug: true in config to log cache hits/misses.Cache Staleness:
Cache annotation’s vary parameter (if supported) or manual invalidation.Annotation Parsing:
@Cache annotation must be parsed by Doctrine’s annotation reader. Ensure doctrine/annotations is installed:
composer require doctrine/annotations
Configuration Overrides:
config.yml takes precedence over annotations. Test changes thoroughly.PHP 7+ Compatibility:
debug: true to log cache operations to var/log/dev.log.cache_dir is writable and not symlinked (some systems break cache writes).php app/console cache:clear if cache behaves unexpectedly.Custom Cache Backend:
Extend the bundle by implementing BigYouth\PageCacheBundle\Cache\CacheInterface and bind it as a service.
Event Listeners:
Listen to big_youth_page_cache.invalidate events for custom invalidation logic:
// src/EventListener/CacheListener.php
public function onCacheInvalidate(CacheInvalidateEvent $event)
{
// Custom logic (e.g., log, notify)
}
Middleware Alternative: For Symfony 4.3+, consider replacing annotations with middleware for better flexibility:
// src/Kernel.php
protected function build(RequestContext $requestContext)
{
$requestContext->addMiddleware(new PageCacheMiddleware());
}
How can I help you explore Laravel packages today?