1.06.2012

Yii Caching example

In order to use caching in yii framework you need define in main.php file and choose type of caching. Here are some examples.

Normal data caching
  1. // data cache
  2. public function actionCache()
  3. {
  4.     $cache = Yii::app()->cache;
  5.     //get cache
  6.     $time = $cache->get('cache_key');
  7.     //if cache is gone.
  8.     if (false === $time){  
  9.       //set cache
  10.       $cache->set('cache_key',time(),30);
  11.       $time = $cache->get('cache_key');
  12.     }
  13.     echo $time;
  14. }


Fregment data caching
  1. // fregment data cache
  2. public function actionCache()
  3. {
  4.   if ($this->beginCache('cache_key',
  5.   array('duration'=>60,
  6.         'dependency'=>array(
  7.       'class'=>'system.caching.dependencies.CDbCacheDependency',//you must have db set here
  8.       'sql'=>'SELECT COUNT(*) FROM  `user`',//you must have db set here
  9.   ),
  10.   'varyByParam'=>array('id'),//cache by $_GET['id']
  11.   ))){
  12.       echo 'cache_key'.time();
  13.       echo @$_GET['id'];
  14.       echo ' <hr /> ';
  15.       $this->endCache();
  16.   }
  17. }


Page Cache
  1. public function filters()
  2. {
  3.     return array(
  4.         array('COutputCache + PageCache', 'duration'=>30,'varyByParam'=>array('id')),
  5.     );
  6. }
  7. public function actionCache()
  8. {
  9.     $this->render('pageCache');
  10. }

It's easy to use, just to be a bit change. More about yii caching visit this: http://www.yiiframework.com/doc/guide/1.1/en/caching.overview

No comments:

Post a Comment