Refine Post By:

Magento comes with a fully featured caching system to help improve your stores performance. Block caching at times can be frustrating when dealing with dynamic content. Disabling block caching will result in a loss of performance, but having it enabled wont allow you to have dynamic content within those blocks. Magento was smart enough to enhance the getChildHtml method to give us more leverage over blocks — granting us the ability to bypass caching on the blocks that we’re interested in keeping dynamic. In order to fully grasp the concept of this technique, you’re going to need to understand Magento Theming and how blocks work.

Let’s look the Method Summary for getChildHtml

1
string getChildHtml ([string $name = ‘’], [boolean $useCache = true], [ $sorted = true])

Notice the second argument? It accepts a true or false value but defaults to true if it’s not defined. Not many people know this. All you have to do is set it to false in order to avoid caching the block. Simple right?

1
getChildHtml('header',false);

Voila! Your header isn’t going to be cached anymore!

Block Caching Expiration

There are other ways to manage caching for specified blocks, but the technique is a little more involved and allows you to set caching expiration on blocks. You do this by setting an expiration time in the block constructor. In this example we’re going to expire the cache after 120 seconds.

1
2
3
4
5
6
7
8
    class myNameSpace_myModule_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),
            ));
        }        
    }

And you’re done! Hope this was helpful.

If you have want to learn more about block caching, take a look at this article Block Cache and HTML Output.

No Comments

Leave a comment