When we talk about Magento, we should try to optimize site loading speed as much as possible.
Sometimes the block caching is not enough and we should also use collection caching to achieve best results.

Here is a simple way to use the cached collection in Magento.
Let’s add this method in our class where we will create and use Magento collection:

public function _prepareCollectionCache($collection)
{
    if (Mage::app()->useCache('collections')) {
 
        $cache = Mage::app()->getCache(); //Let's get cache instance
        $cache->setLifetime(86400); //Here we set collection cache lifetime
 
        $collection->initCache(
            $cache,
            'Bestsellers_', //this is just custom prefix
            array('collections') 
        );
    }
 
    return $collection;
}

After that, when our collection is prepared, let’s just pass it through method above.
For example:

...
        $categoriesCollection = Mage::getModel('catalog/category')->getCollection();
 
        $categoriesCollection->addAttributeToSelect('name');
        $categoriesCollection->addFieldToFilter('entity_id', array('in' => $catIds));
 
        $categoriesCollection->addFieldToFilter('is_active', array('eq' => true));
        $categoriesCollection->getSelect()->order(array('level DESC'));
 
        $categoriesCollection = $this->_prepareCollectionCache($categoriesCollection);
...

That is basically all. Our category collection will be cached from now on.

If you are interested what is actually happening and how this collection caching mechanism works, just take a look at Varien_Data_Collection_Db class which is one of the parent classes that every Magento collection extends.

It contains a whole caching mechanism which uses parameters that we provided by calling “initCache” on collection object.

I hope that you will find this little tip useful. Cheers


Leave a Reply

Your email address will not be published. Required fields are marked *