Page tree
Skip to end of metadata
Go to start of metadata

The output html of a block can be saved in the Magento cache.

For the moment, there’s nearly no blocks saved in the default Magento store, except the frontend and admin headers.

Example 1

The cache management has to be written in the constructor of the Block :

class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
 
    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 120,
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
        ));
    }   
 
} 

In this exemple, we have a time to live of 120 seconds. The output code will be saved in cache until the “Product” cache will be deleted.

Consequences :

  • Any product save will delete this cache
  • This code is OK if and only if the output does not depend of a specific product. If you are doing so for the product view, all your products will have the same output !

Example 2

Then, let’s consider the following example :

 class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
 
    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 120,
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
            'cache_key'            => $this->getProduct()->getId(),
        ));
    }   
 
}

Consequences :

  • The output will be different depends of your product id.
  • Any product save will delete this cache

Example 3

Finally, we have :

 class {NS}_{Module}_Block_{View} extends Mage_Core_Block_Template {
 
    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 120,
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG . "_" . $this->getProduct()->getId()),
            'cache_key'            => $this->getProduct()->getId(),
        ));
    }
   
}

Consequences :

  • The output will be different depending of your product id.
  • Only a change of the specified product will delete the cache.

This example only works for products... If you want to do the same thing for category, you should override the Model and add :

    public function cleanCache()
    {
        Mage::app()->cleanCache('catalog_category_'.$this->getId());
    }   
   
    protected function _beforeSave() {
        $this->cleanCache();
        return parent::_beforeSave();
    } 

Tips

If cache_lifetime is equal to false, it means that the cache will never expire.

 

 

  • No labels