2011-04-14 11:26:40 1 评论 Yii 1.0 Boy.Lee

Yii 1.0 缓存示例代码

{Normal Cache}

//data cache
public function actionTestCache()
{
//      print_r(Yii::app()->cache);  //check the value
    $cache = Yii::app()->cache;
    $time = $cache->get('BoyLee001'); //get cache
    if (false === $time){  //if cache is gone.
    $cache->set('BoyLee001',time(),30); //set cache
//    $cache['BoyLee001'] = $time();  //this is not right.
    $time = $cache->get('BoyLee001');
    }
    echo $time;
}

{Fregment Cache}

//fregment cache
public function actionFregmentCache()
{
  if ($this->beginCache('BoyLee002',
  array('duration'=>60,
        'dependency'=>array(
      'class'=>'system.caching.dependencies.CDbCacheDependency',//you must have db set here
      'sql'=>'SELECT COUNT(*) FROM  `user`',//you must have db set here
  ),
  'varyByParam'=>array('id'),//cache by $_GET['id']
  ))){
      echo 'BoyLee'.time();
      echo @$_GET['id'];
      echo ' <hr /> ';
      $this->endCache();
  }
}

{PageCache}

{controller}

  public function filters()
  {
      return array(
          array('COutputCache + PageCache', 'duration'=>30,'varyByParam'=>array('id')),
      );
  }
  public function actionPageCache()
  {
      $this->render('pageCache');
  }

{view pageCache.php}

echo time();
echo ' <hr /> ';
echo @$_GET['id'];

{Boy Say}

跟随我上述代码可以很容易的掌握在Yii1.0框架中使用缓存,然后再根据需要进行调整.