andres-montanez/fragment-cache-bundle
Installation:
composer require andres-montanez/fragment-cache-bundle
Enable the bundle in app/AppKernel.php:
new AndresMontanez\FragmentCacheBundle\AndresMontanezFragmentCacheBundle(),
First Use Case: Cache a Twig-embedded sub-request (e.g., a footer or sidebar) by annotating the controller:
use AndresMontanez\FragmentCacheBundle\Annotation\FragmentCache;
class IndexController extends Controller
{
/**
* @FragmentCache()
*/
public function footerAction()
{
return $this->render('AcmeDemoBundle:Index:footer.html.twig');
}
}
In Twig:
{{ render(controller('AcmeDemoBundle:Index:footer')) }}
Configuration:
Check app/config/config.yml for default cache settings (e.g., fragment_cache_lifetime).
Override as needed:
fragment_cache:
lifetime: 3600 # 1 hour in seconds
namespace: 'fragment_'
Caching Dynamic Fragments: Use annotations with dynamic keys for personalized fragments:
/**
* @FragmentCache(key="user_dashboard_$userId")
*/
public function userDashboardAction($userId)
{
// ...
}
Conditional Caching: Skip caching for non-GET requests or when data changes:
/**
* @FragmentCache(skipIf="request.method != 'GET' || $isDataUpdated")
*/
public function dynamicContentAction()
{
// ...
}
Integration with Symfony Cache:
Leverage Symfony’s cache system (e.g., cache:pool:clear) to invalidate fragments:
php bin/console cache:clear fragment_
cache:pool:clear fragment_user_*).fragment_cache.debug in config to log cache hits/misses.Deprecated Bundle:
spatie/laravel-fragment-cache for Laravel.Annotation Limitations:
fragment_cache.namespace isn’t unique.Cache Invalidation:
cache:clear).var/cache/dev/) for cached fragments.
ls var/cache/dev/fragment_*
fragment_cache:
debug: true
Custom Cache Drivers:
Override the default cache pool in AndresMontanez\FragmentCacheBundle\DependencyInjection\Compiler\CachePass.
Example: Use Redis instead of filesystem.
Dynamic Keys:
Extend the FragmentCache annotation to support closures for key generation:
/**
* @FragmentCache(key="dynamic_key_$(someLogic())")
*/
Laravel Alternative:
For Laravel, use spatie/laravel-fragment-cache with similar patterns:
use Spatie\FragmentCache\Facades\Fragment;
Fragment::cache('sidebar', now()->addMinutes(30), function () {
return view('partials.sidebar');
});
How can I help you explore Laravel packages today?