Magento – Magento 1.9 Cache Custom Block Data

block-cachecachecollection;

I have a custom module that displays products from a given category in a carousel. Now, I was wanting to cache the results, so the database is not queried and duly for speed optimisation.

However, I am unaware of how to correctly incorporate caching into the module. Thus, was wondering if a kind soul could help me.

I have attempted to cache the block, via the construct and getcachekeyinfo functions. But, I am unsure if this is correct. Like would the collection data be cached like this? or just the html ?

Model.php

<?php

class Pcarousel_Pcarousel_Model_Pcarousel extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('pcarousel/pcarousel');
    }
}

Helper/Data.php

<?php

class Pcarousel_Pcarousel_Helper_Data extends Mage_Core_Helper_Abstract
{


    public function getAllCategoriesArray($optionList = false)
{
    $categoriesArray = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('entity_id')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();

    if (!$optionList) {
        return $categoriesArray;
    }

    foreach ($categoriesArray as $categoryId => $category) { 
        if (isset($category['name'])) {
            $categories[] = array(
                'value' => $category['entity_id'],
                'label' => Mage::helper('pcarousel')->__($category['name'])
            );
        }
    }

    return $categories;
}

}

controllers/indexcontroller.php

<?php
class Pcarousel_Pcarousel_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {

        /*
         * Load an object by id 
         * Request looking like:
         * http://example.com/pcarousel?id=15 
         *  or
         * http://example.com/pcarousel/id/15   
         */
        /* 
        $pcarousel_id = $this->getRequest()->getParam('id');

        if($pcarousel_id != null && $pcarousel_id != '')    {
            $pcarousel = Mage::getModel('pcarousel/pcarousel')->load($pcarousel_id)->getData();
        } else {
            $pcarousel = null;
        }   
        */

         /*
         * If no param we load a the last created item
         */ 
        /*
        if($pcarousel == null) {
            $resource = Mage::getSingleton('core/resource');
            $read= $resource->getConnection('core_read');
            $pcarouselTable = $resource->getTableName('pcarousel');

            $select = $read->select()
               ->from($pcarouselTable,array('pcarousel_id','title','content','status'))
               ->where('status',1)
               ->order('created_time DESC') ;

            $pcarousel = $read->fetchRow($select);
        }
        Mage::register('pcarousel', $pcarousel);
        */


        $this->loadLayout();     
        $this->renderLayout();
    }

    public function aaction()
    {

        $this->loadLayout();     
        $this->renderLayout();
    }
}

block/pcarousel.php

   <?php
class Pcarousel_Pcarousel_Block_Pcarousel extends Mage_Core_Block_Template
{
    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime' => 3600,
            'cache_tags'        => array(Mage_Core_Model_Store::CACHE_TAG, Mage_Cms_Model_Block::CACHE_TAG)
        ));
    }
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

     public function getInsurance()     
     { 
        if (!$this->hasData('pcarousel')) {
            $this->setData('pcarousel', Mage::registry('pcarousel'));
        }
        return $this->getData('pcarousel');

    }
    public function getCacheKeyInfo()
{
    return array(
        $this->getData('pcarousel_id'),
        Mage::app()->getStore()->getId(),
        (int)Mage::app()->getStore()->isCurrentlySecure(),
        Mage::getDesign()->getPackageName(),
        Mage::getDesign()->getTheme('template')
    );
}
}

Best Answer

Below I have explain how to cache your result in simple way.

<?php
class Pcarousel_Pcarousel_Helper_Data extends Mage_Core_Helper_Abstract
{
    const CACHE_KEY = 'Pcarousel_AllCategories_';
    const CACHE_LIFE_TIME = 86400;
    const CACHE_GROUP = 'Pcarousel_AllCategories_list';

    public function getAllCategoriesArray($optionList = false)
    {
        $cacheKey = $this->_getCacheKey('AllCategoriesArray');
        $responseRresult = Mage::app()->loadCache($cacheKey);

        if (empty($responseRresult)) {
            $categoriesArray = Mage::getModel('catalog/category')
                ->getCollection()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('entity_id')
                ->addAttributeToSort('path', 'asc')
                ->addFieldToFilter('is_active', array('eq'=>'1'))
                ->load()
                ->toArray();

            if (!$optionList) {
                return $categoriesArray;
            }

            foreach ($categoriesArray as $categoryId => $category) { 
                if (isset($category['name'])) {
                    $categories[] = array(
                        'value' => $category['entity_id'],
                        'label' => Mage::helper('pcarousel')->__($category['name'])
                    );
                }
            }
            $this->_saveCache($cacheKey,$categories);
            return $categories;
        }   

        return unserialize($responseRresult);
    }

    /**
     * create key 
     * @return string
     */
    public function _getCacheKey($keyValue)
    {
        $websiteId = Mage::app()->getWebsite()->getId();
        $cacheKey = self::CACHE_KEY .$websiteId.'_'.$keyValue;
        unset($keyValue);
        return $cacheKey;
    }

    /**
     * save cache
     * @param mixed $value
     * 
     */
    public function _saveCache($cacheKey,$value)
    {
        Mage::app()->saveCache(serialize($value),
        $cacheKey, 
        array(self::CACHE_GROUP),
        self::CACHE_LIFE_TIME);
    }   

}

If you wand to clean cache using crone then put below code in crone file

Mage::app()->cleanCache('self::CACHE_GROUP');