Cashing Magento block is quite a simple task. Let’s see how it works.
1 2 3 4 5 6 7 8 9 10 11 |
class The_Name_of_The_Block_Class_We_Need extends Mage_Core_Block_Template { protected function _construct() { $this->addData(array( 'cache_lifetime' => self::LIFE_TIME, 'cache_tags' => array(self::CACHE_TAG), 'cache_key' => self::CACHE_KEY, )); } } |
We’ll start with an example. Let’s assume you have a client who wants his store to work faster than it does at the moment. Let’s, help him.
Problem 1: A block of a module doesn’t work as fast as it should. It doesn’t matter if this module is yours or not. You can re-write this block, but it won’t solve the problem. Modules tend to update.
Problem 2: There are several templates on the page which use our block.
As a solution let’s use observers. A pretty easy solution in my opinion. You don’t have to change other’s code when there’s another solution. But If you decide that the code changes are necessary – ignore my recommendations.
There are different solutions to deal with the second problem. The most important thing is to find the difference between blocks on the page. You’re going to use these differences in the cache key. For my example I chose Alias blocks that were mentioned in Layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<frontend> <events> <core_block_abstract_to_html_before> <observers> <belvg_block_to_html_before> <type>singleton</type> <class>the_extension_name/observer</class> <method>initBlockCache</method> </belvg_block_to_html_before> </observers> </core_block_abstract_to_html_before> . . . . . </events> . . . . . </frontend> |
1 2 3 4 5 6 7 8 9 10 11 12 |
public function initBlockCache(Varien_Event_Observer $observer) { $block = $observer->getEvent()->getBlock(); if ($block instanceof the_name_of_the_block_class_we_need) { $block->addData(array( 'cache_lifetime' => self::LIFE_TIME, 'cache_tags' => array(self::CACHE_TAG), 'cache_key' => self::CACHE_KEY . '_' . $block->getBlockAlias() . '_store' . Mage::app()->getStore()->getId(), )); } } |