Quick tips to work with joomla caching in different joomla versions

Here just some quick tips about how to use joomla caching in joomla extensions , here for module and component.

For joomla 1.5 module caching:


//$params, $module are global parameter here , can be used in default.php or have to pass in helper method.
$enable_cache 		=   $params->get('cache',0);
$cachetime		=   $params->get('cache_time',0);
//for 1.5
if($enable_cache == 1) {
    $conf =& JFactory::getConfig();
    $cache = &JFactory::getCache($module->module);
    $cache->setLifeTime( $params->get( 'cache_time', $conf->getValue( 'config.cachetime' ) * 60 ) );
    $cache->setCaching(true);
    $cache->setCacheValidation(true);
    $output =  $cache->get( array('modClassname', 'getMethod'), array($params, $module));
} else {
    $output = modClassname::getMethod($params,$module);
}

For joomla 1.6 we do the same thing in following way

$cacheparams = new stdClass;
$cacheparams->cachemode = 'safeuri';
$cacheparams->class = 'modClassname';
$cacheparams->method = 'getMethod';
$cacheparams->methodparams = array($params,$module);
$cacheparams->modeparams = array('id'=>'int','Itemid'=>'int');
$output = JModuleHelper::moduleCache ($module, $params, $cacheparams);

For joomla 1.5 and 1.6 compatibility we can code like this which will work for both joomla version

$enable_cache 		=   $params->get('cache',0);
$cachetime		=   $params->get('cache_time',0);
if(version_compare(JVERSION,'1.6.0','ge')) {
    $cacheparams = new stdClass;
    $cacheparams->cachemode = 'safeuri';
    $cacheparams->class = 'modClassname';
    $cacheparams->method = 'getMethod';
    $cacheparams->methodparams = array($params,$module);
    $cacheparams->modeparams = array('id'=>'int','Itemid'=>'int');
    $output = JModuleHelper::moduleCache ($module, $params, $cacheparams);
}
else{
    //for 1.5
    if($enable_cache == 1) {
            $conf =& JFactory::getConfig();
            $cache = &JFactory::getCache($module->module);
            $cache->setLifeTime( $params->get( 'cache_time', $conf->getValue( 'config.cachetime' ) * 60 ) );
            $cache->setCaching(true);
            $cache->setCacheValidation(true);
            $output =  $cache->get( array('modClassname', 'getMethod'), array($params, $module));
    } else {
            $output = modClassname::getMethod($params,$module);
    }
}

Note: here I assumed the modClassname is the class name of the helper and modMethod is the method used to handle the caching part. In next post I will write something about the component caching and in 3rd one post about how to caching when we are not doing any function call or how about handle caching in plugin. Let me have time for the next post.

Leave a Reply

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