Installation Add the bundle via Composer:
composer require datafactory/http-cache-bundle
Enable the bundle in config/bundles.php:
DataFactory\FOSHttpCacheBundle\DataFactoryFOSHttpCacheBundle::class => ['all' => true],
Configuration Publish the default config:
php bin/console fos:http-cache:install
Edit config/packages/datafactory_fos_http_cache.yaml to define:
short, long).proxy_client, vary).purge_url).First Use Case
Cache a route response with a short profile:
use Symfony\Component\HttpFoundation\Response;
use DataFactory\FOSHttpCacheBundle\Annotation\Cache;
class MyController
{
/**
* @Cache(profile="short")
*/
public function index(): Response
{
return new Response('Cached content');
}
}
@Cache on controller methods or routes (@Route).
# config/routes.yaml
my_route:
path: /cached
controller: App\Controller\MyController::index
methods: GET
cache: { profile: "long" }
$this->cache->setProfile($request->query->get('cache_profile'));
php bin/console fos:http-cache:purge /path/to/invalidate
$this->cache->purge('/path/to/invalidate');
fos_http_cache.purge events:
use DataFactory\FOSHttpCacheBundle\Event\PurgeEvent;
$eventDispatcher->addListener(PurgeEvent::class, function (PurgeEvent $event) {
// Custom logic (e.g., log, notify)
});
vary headers dynamically:
$this->cache->setVary(['Accept-Language', 'User-Agent']);
$this->cache->setTTL(3600); // Override for 1 hour
HttpCache service directly:
$this->httpCache->getResponse($request);
proxy_client backend for Varnish/Nginx:
# config/packages/datafactory_fos_http_cache.yaml
proxy_client:
backend: varnish
host: 127.0.0.1
port: 6081
Cache Headers Conflicts
Cache-Control headers from the bundle don’t clash with other middleware (e.g., Symfony’s HttpCache).private/public in profiles:
profiles:
short:
max_age: 3600
public: true
Invalidation Race Conditions
purge_batch for bulk invalidations:
php bin/console fos:http-cache:purge_batch /path1 /path2
Vary Headers Overhead
Vary headers can bloat responses and reduce cache efficiency.vary to critical headers (e.g., Accept-Language).bin/console debug:headers to verify cache headers.# config/packages/dev/datafactory_fos_http_cache.yaml
debug: true
Custom Backends
Extend DataFactory\FOSHttpCacheBundle\Cache\Backend\AbstractBackend for new cache types (e.g., Redis).
Profile Factories
Dynamically generate profiles via ProfileFactoryInterface:
$factory = $this->container->get('fos_http_cache.profile_factory');
$profile = $factory->create('dynamic_profile', ['ttl' => 7200]);
Event Subscribers
Hook into fos_http_cache.response to modify responses before caching:
public static function getSubscribedEvents()
{
return [
'fos_http_cache.response' => 'onCacheResponse',
];
}
proxy_client for edge caches (Varnish, Cloudflare) over vary.profiles:
static:
max_age: 31536000
vary: []
How can I help you explore Laravel packages today?