Reputation: 1078
I need to distinguish further regarding cache-states for the http-cache. There are two additional parameters, that I want to take into account when caching the response with the HttpCache:
How can this be achieved?
Upvotes: 0
Views: 298
Reputation: 1078
I think I found the answer: there is \Shopware\Storefront\Framework\Cache\Event\HttpCacheGenerateKeyEvent
which is dispatched during the build of the cache-hash (which is used to look up if there is already a cached response or not).
By creating a subscriber to this event you can modify the cache hash taking your own parameters into regard. So for my example, it would look like something like this:
class CacheKeySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
HttpCacheGenerateKeyEvent::class => 'onGenerateCacheKey',
];
}
public function onGenerateCacheKey(HttpCacheGenerateKeyEvent $event): void
{
$request = $event->getRequest();
$originalHash = $event->getHash();
$countryHeaderValue = $request->headers->get('cf-ipcountry');
$exampleCookieValue = $request->cookies->get('example-cookie');
$dataToHash = '';
if ($countryHeaderValue) {
$dataToHash .= '-country:' . $countryHeaderValue;
}
if ($exampleCookieValue) {
$dataToHash .= '-exampleCookieValue:' . $exampleCookieValue;
}
$newHash = hash('sha256', $originalHash . $dataToHash);
$event->setHash($newHash);
}
}
Upvotes: 1