英文:
How to add additional cache-states for HttpCache in Shopware 6?
问题
我需要进一步区分http缓存的缓存状态。在使用HttpCache缓存响应时,有两个额外的参数我想要考虑:
- 请求中Cloudflare头部 "cf-ipcountry" 的值
- 请求中可以设置的额外cookie的值,我们称之为 "example-cookie"
如何实现这一点?
英文:
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:
- The value of the Cloudflare header "cf-ipcountry" in the request
- the value of an additional cookie that can be set during the request, lets call it "example-cookie"
How can this be achieved?
答案1
得分: 1
我认为我找到了答案:有一个名为\Shopware\Storefront\Framework\Cache\Event\HttpCacheGenerateKeyEvent
的事件,在缓存哈希生成期间触发(用于查找是否已经有缓存响应)。
通过创建一个订阅者来监听此事件,您可以修改缓存哈希,考虑您自己的参数。因此,对于我的示例,代码看起来可能类似于以下内容:
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);
}
}
希望这对您有帮助。
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论