在插件中停用 Shopware 5 中的 HTTP 缓存

Deactivate HTTP cache in Shopware 5 in a plugin

在一个插件中,我需要为两个类别停用 Shopware HTTP-Cache。 manual 说我应该发出这个事件:

Shopware()->Events()->notify(
    'Shopware_Plugins_HttpCache_InvalidateCacheId',
    array(
        'cacheId' => 'a14',
    )
);

a14代表ID为14的文章。根据手册a c可以用来uncache category pages。所以我把它放在我的插件中 bootstrap.php 以停止缓存 ID 为 113 和 114 的类别:

public function afterInit()
{
    Shopware()->Events()->notify(
        'Shopware_Plugins_HttpCache_InvalidateCacheId',
        array(
            'cacheId' => 'c113',
            'cacheId' => 'c114',
        )
    );
}

我已经在所有级别上手动清空了缓存,但没有任何反应,无论好坏,都没有抛出错误,清空后重建缓存时,类别也没有从缓存中删除。有人知道我应该更改什么吗?

这是完整的解决方案,感谢 Thomas 的回答,一切都在 Bootstrap.php:

首先订阅PostDispatch_Frontend_Listing事件:

public function install() 
{
    $this->subscribeEvent('Enlight_Controller_Action_PostDispatch_Frontend_Listing', 'onPostDispatchListing');
    return true;
}

其次创建一个在特定条件下发送 no-cache-header 的函数:

public function onPostDispatchListing(Enlight_Event_EventArgs $arguments)
{
    $response = $arguments->getResponse();
    $categoryId = (int)Shopware()->Front()->Request()->sCategory;
    if ($categoryId === 113 || $categoryId === 114) {
        $response->setHeader('Cache-Control', 'private, no-cache');
    }
}

第三次安装或重新安装插件,这样对事件的订阅将保留在数据库中。

我认为最好的方法是添加一个插件,为指定类别的响应添加 Cache-Control: no-cache header。设置此 header 后,类别不会存储在 HTTP 缓存中,您无需使其无效。

您可以监听 Enlight_Controller_Action_PostDispatch_Frontend_Listing 事件并检查类别 ID 是否是您需要的,然后将 header 添加到响应中。

$response->setHeader('Cache-Control', 'private, no-cache');