在main.php的组件components中配置设置添加缓存
'cache'=>array(
'class' => 'system.caching.CFileCache'
),
也就是framework/caching/CFileCache.php
片段缓存
在模板中使用
<?php if($this->beginCache('bolg_index',array('duration'=>3600))): ?>
.
.
.
<?php $this->endCache();endif ?>
整页缓存
在控制器中设置 filters 方法,注意不要忘记了varyByParam,负责生成的页面都是一样的
public function filters(){
return array(
array(
'system.web.widgets.COutputCache + index',
'duration' => 3600,
'varyByParam'=> array('id')
)
);
}
数据缓存
数据缓存加分页实例
public function actionIndex($id){
$page = max(intval(@$_GET['page']),1);
$data = Yii::app()->cache->get('blog_category_'.$id.'_'.$page);
if($data == false){
$model = Article::model();
$total = $model->count("catid = $id");//统计总条数
$pager = new CPagination($total);//实例化分页类
$pager->pageSize = 4;//每页显示多少条
$limit = (($page-1)*4).',4';
//查询数据
$info = $model->findAllBySql("select id,title,thumb,description,inputtime from {{article}} where catid = $id order by id desc limit $limit");
$data = array("articleInfo"=>$info,"pages"=>$pager);
Yii::app()->cache->set('blog_category_'.$id.'_'.$page, $data,3600);
}
$this->render("index",$data);
}