yii2的 数据缓存-片段缓存-片段缓存-HTTP缓存

数据缓存:将一些 PHP 变量存储到缓存中,使用时再从缓存中取回。

如:页面中显示博客文章总数


片段缓存:缓存页面内容中的某个片段。

如:一个页面显示了逐年销售额的摘要表格,可以把表格缓存下来,以消除每次请求都要重新生成表格的耗时。

如:标签云,见如下代码


页面缓存:在服务器端缓存整个页面的内容。随后当同一个页面被请求时,内容将从缓存中取出,而不是重新生成。


HTTP缓存:利用客户端缓存去节省相同页面内容的生成和传输时间。








总结:










frontend/Controller/PostController.php

<?php

namespace frontend\controllers;

use Yii;
use common\models\Post;
use common\models\PostSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use common\models\Tag;
use common\models\Comment;
use common\models\User;
use yii\rest\Serializer;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends Controller
{
	public $added=0; //0代表还没有新回复
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        			
            'access' =>[
            		'class' => AccessControl::className(),
            		'rules' =>
            		[
            			[
            				'actions' => ['index'],
            				'allow' => true,
            				'roles' => ['?'],
            			],
            			[
            				'actions' => ['index', 'detail'],
            				'allow' => true,
            				'roles' => ['@'],
            	         ],
            		],
            ],
        		
        	'pageCache'=>[
        			'class'=>'yii\filters\PageCache',
        			'only'=>['index'],
        			'duration'=>600,
        			'variations'=>[
        					Yii::$app->request->get('page'),
        					Yii::$app->request->get('PostSearch'),
        			],
        			'dependency'=>[
        					'class'=>'yii\caching\DbDependency',
        					'sql'=>'select count(id) from post',
        			],
        	],
        		
        	'httpCache'=>[
        			'class'=>'yii\filters\HttpCache',
        			'only'=>['detail'],
        			'lastModified'=>function ($action,$params){
        				$q = new \yii\db\Query();
        				return $q->from('post')->max('update_time');
        			},
        			'etagSeed'=>function ($action,$params) {
        				$post = $this->findModel(Yii::$app->request->get('id'));
        				return serialize([$post->title,$post->content]);
        			},
        			
        			'cacheControlHeader' => 'public,max-age=600',
        			
        	],
        		
        		
        ];
    }

    /**
     * Lists all Post models.
     * @return mixed
     */
    public function actionIndex()
    {
    	$tags=Tag::findTagWeights();
    	$recentComments=Comment::findRecentComments();
    	
        $searchModel = new PostSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        	'tags'=>$tags,
        	'recentComments'=>$recentComments,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Post model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Post();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Post model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Post model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionDetail($id)
    {
    	//step1. 准备数据模型   	
    	$model = $this->findModel($id);
    	$tags=Tag::findTagWeights();
    	$recentComments=Comment::findRecentComments();
    	
    	$userMe = User::findOne(Yii::$app->user->id);
    	$commentModel = new Comment();
    	$commentModel->email = $userMe->email;
    	$commentModel->userid = $userMe->id;
    	
    	//step2. 当评论提交时,处理评论
    	if($commentModel->load(Yii::$app->request->post()))
    	{
    		$commentModel->status = 1; //新评论默认状态为 pending
    		$commentModel->post_id = $id;
    		if($commentModel->save())
    		{
    			$this->added=1;
    		}
    	}
    	
    	//step3.传数据给视图渲染
    	return $this->render('detail',[
    			'model'=>$model,
    			'tags'=>$tags,
    			'recentComments'=>$recentComments,
    			'commentModel'=>$commentModel, 
    			'added'=>$this->added, 			
    	]);
    	
    }
 
}

frontend/views/post/index.php
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\ListView;
use frontend\components\TagsCloudWidget;
use frontend\components\RctReplyWidget;
use common\models\Post;
use yii\caching\DbDependency;
use yii\caching\yii\caching;

/* @var $this yii\web\View */
/* @var $searchModel common\models\PostSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

?>

<div class="container">

	<div class="row">
	
		<div class="col-md-9">
		
		<ol class="breadcrumb">
		<li><a href="<?= Yii::$app->homeUrl;?>">首页</a></li>
		<li>文章列表</li>
		
		</ol>
		
		<?= ListView::widget([
				'id'=>'postList',
				'dataProvider'=>$dataProvider,
				'itemView'=>'_listitem',//子视图,显示一篇文章的标题等内容.
				'layout'=>'{items} {pager}',
				'pager'=>[
						'maxButtonCount'=>10,
						'nextPageLabel'=>Yii::t('app','下一页'),
						'prevPageLabel'=>Yii::t('app','上一页'),
		],
		])?>
		
		</div>

		
		<div class="col-md-3">
			<div class="searchbox">
				<ul class="list-group">
				  <li class="list-group-item">
				  <span class="glyphicon glyphicon-search" aria-hidden="true"></span> 查找文章(
				  <?php 
				  //数据缓存示例代码
				  /*
				  $data = Yii::$app->cache->get('postCount');
				  $dependency = new DbDependency(['sql'=>'select count(id) from post']);
				  
				  if ($data === false)
				  {
				  	$data = Post::find()->count();  sleep(5);
				  	Yii::$app->cache->set('postCount',$data,600,$dependency); //设置缓存60秒后过期
				  }
				  
				  echo $data;
				  */
				  ?>
				  <?= Post::find()->count();?>
				  )
				  </li>
				  <li class="list-group-item">				  
					  <form class="form-inline" action="<?= Yii::$app->urlManager->createUrl(['post/index']);?>" id="w0" method="get">
						  <div class="form-group">
						    <input type="text" class="form-control" name="PostSearch[title]" id="w0input" placeholder="按标题">
						  </div>
						  <button type="submit" class="btn btn-default">搜索</button>
					</form>
				  
				  </li>
				</ul>			
			</div>
			
			<div class="tagcloudbox">
				<ul class="list-group">
				  <li class="list-group-item">
				  <span class="glyphicon glyphicon-tags" aria-hidden="true"></span> 标签云
				  </li>
				  <li class="list-group-item">
				  <?php 
				  //片段缓存示例代码
				  /*
				  $dependency = new DbDependency(['sql'=>'select count(id) from post']);
				  
				  if ($this->beginCache('cache',['duration'=>600],['dependency'=>$dependency]))
				  {
				  	echo TagsCloudWidget::widget(['tags'=>$tags]);
				  	$this->endCache();
				  }
				  */
				  ?>
				  <?= TagsCloudWidget::widget(['tags'=>$tags]);?>
				   </li>
				</ul>			
			</div>
			
			
			<div class="commentbox">
				<ul class="list-group">
				  <li class="list-group-item">
				  <span class="glyphicon glyphicon-comment" aria-hidden="true"></span> 最新回复
				  </li>
				  <li class="list-group-item">
				  <?= RctReplyWidget::widget(['recentComments'=>$recentComments])?>
				  </li>
				</ul>			
			</div>
			
		
		</div>
		
		
	</div>

</div>

====================================================================================

 视频:http://www.yiichina.com/video

源代码下载:https://github.com/michaelweixi/blogdemo2/archive/V1.17.tar.gz


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值