Magento – Cache problem – prevent the module block to be cached

block-cacheblockscachefull-page-cachevarnish

I have a module which includes block to each page. The block template prints javascript which displays notification to user.

First I defined observer in module config file:

 <frontend> 
    <events>
        <controller_action_layout_load_before>
            <observers>
                <mymodule_add_block_at_end_of_main_content>
                    <type>singleton</type>
                    <class>mymodule/observer</class>
                    <method>addBlockAtEndOfMainContent</method>
                </mymodule_add_block_at_end_of_main_content>
            </observers>
        </controller_action_layout_load_before>
    </events>  
 </frontend>   

Then model

class Company_Mymodule_Model_Observer
{
    public function addBlockAtEndOfMainContent(Varien_Event_Observer $observer)
    {        
        $layout = $observer->getEvent()->getLayout()->getUpdate();
        $layout->addHandle('add_my_block');
        return $this;
    }
}

And layout file

<layout>       
    <add_my_block>  
      <reference name="content">
          <block type="mymodule/mymodule" name="myblockname" after="-" template="mymodule/notification.phtml"/>
      </reference>                                                
    </add_my_block>
</layout>

When user closes notification, cookie is stored. Inside mymodule.php I check with php if cookie exists. If exists, the notification with that cookie is not showed again.

$collection->addFieldToFilter('cookie_id',array('nin' => $deniedIds))

THE PROBLEM:

This module is installed on many stores and some of them have cache modules, such as Varnish cache and others. Some of cache modules cache my module block and therefore notification is showed every time, no matter if user closed it. It doesn't come to addFieldToFilter because the entire block was already cached.

Does anybody have any idea how I can avoid this? Is any better way to include the block to each page and not being cached?

Thank you!

Best Answer

I realized that Varnish caches entire html, so there is no way to partially exclude block to be cached. My solution in this case is to make ajax request with POST parameter. POST request is not cached.

Related Topic