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')
 );
}
}
1 Answer 1
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 want to clean cache using cron then put below code in cron file:
Mage::app()->cleanCache(Pcarousel_Pcarousel_Helper_Data::CACHE_GROUP);
- 
 shorabh Wouldn't getCacheKeyInfo do the caching automatically?Vaishal Patel– Vaishal Patel2018年07月19日 15:19:23 +00:00Commented Jul 19, 2018 at 15:19
- 
 @Vaishal cache is Not create automatically. we are using _getCacheKey($key Value) function to create cache key. $cacheKey = $this->_getCacheKey('AllCategoriesArray'); you can pass any parameter.Shorabh– Shorabh2018年07月20日 05:08:01 +00:00Commented Jul 20, 2018 at 5:08
- 
 The way I have above is working though, I am confused.Vaishal Patel– Vaishal Patel2018年07月20日 06:05:13 +00:00Commented Jul 20, 2018 at 6:05
- 
 @vaishal your using getCacheKeyInfo funtion to get cache key i am right . i am using _getCacheKey($key Value) function to generate new cache key . actually i am using key that created my selfShorabh– Shorabh2018年07月20日 06:23:24 +00:00Commented Jul 20, 2018 at 6:23
- 
 Hi @shorabh won't _construct function be setting my cache?Vaishal Patel– Vaishal Patel2018年07月20日 06:28:34 +00:00Commented Jul 20, 2018 at 6:28