Search code examples
shopware

Deactivate HTTP cache in Shopware 5 in a plugin


In a plugin I need to deactivate the Shopware HTTP-Cache for two categories. The manual says I should emit this event:

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

The a14 stands for the article with the ID 14. According to the manual a c can be used to uncache category pages. So I put this in my plugins bootstrap.php to stop caching of the categorys with the ID 113 and 114:

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

I have emptied the cache manually on all levels, but nothing happens, neither good or bad, no error thrown and the categories are not removed from cache when the cache has been rebuild after emptying. Does anybody have a clue what I should change?

Here is the complete solution, thanks to Thomas answer, everything is done in the Bootstrap.php:

First subscribe to the PostDispatch_Frontend_Listing Event:

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

Second create a function to send no-cache-header under certain conditions:

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');
    }
}

Third install or reinstall the plugin so the subscription to the event will be persisted in the database.


Solution

  • I think the best way is to add a plugin which adds a Cache-Control: no-cache header to the response for the specified categories. When this header is set the categories are not stored in the HTTP cache and you don't need to invalidate it.

    You can listen to the Enlight_Controller_Action_PostDispatch_Frontend_Listing event and check if the category id is the one you need and add the header to the response.

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