参考:http://www.yiiframework.com/doc-2.0/guide-caching-overview.html
配置
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
数据缓存
$cache = \Yii::$app->cache;
$cache['aa'] = '123';
echo $cache['aa'];
片段缓存
<h1>朝代</h1>
<?php if($this->beginCache($id, ['duration' => 3600])) { ?>
<?php
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_item',
]);
?>
<?php $this->endCache(); } ?>
$dependency = [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT MAX(updated_at) FROM post',
];
if ($this->beginCache($id, ['dependency' => $dependency])) {
// ... generate content here ...
$this->endCache();
}
if ($this->beginCache($id, ['variations' => [Yii::$app->language]])) {
// ... generate content here ...
$this->endCache();
}
if ($this->beginCache($id1)) {
// ...content generation logic...
if ($this->beginCache($id2, $options2)) {
// ...content generation logic...
$this->endCache();
}
// ...content generation logic...
$this->endCache();
}
页面缓存
class TestController extends Controller
{
public function actionIndex()
{
//$db = \Yii::$app->db;
sleep(2);
$query = Dynasty::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 15,
],
]);
return $this->render('index', [
'dataProvider' => $dataProvider
]);
}
public function behaviors()
{
return [
[
'class' => 'yii\filters\PageCache',
'duration' => 60,
'variations'=> [$_GET['page']],
],
];
}
}
动态内容
...别的HTML内容...
<?php if($this->beginCache($id)) { ?>
...被缓存的片段内容...
<?php $this->renderDynamic($callback); ?>
...被缓存的片段内容...
<?php $this->endCache(); } ?>
...别的HTML内容...