YII Framework http Cache Operation Example

  • 2021-12-11 06:59:53
  • OfStack

This article illustrates the http caching operation of the YII framework. Share it for your reference, as follows:

http Disable Cache Principle


header('Expires: 0');
header('Last-Modified: '. gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cahe, must-revalidate');
//ie Dedicated 
header('Cache-Control: post-chedk=0, pre-check=0', false);
//for HTTP/1.0
header('Pragma: no-cache');

HttpcacheController.php

First, the client lastModified is judged. If the last update time does not change, the cache will not be updated, and then the etagSeed is judged


<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 20:17
 * http  Cache 
 */
namespace frontend\controllers;
use yii;
use yii\web\Controller;
class HttpcacheController extends Controller
{
  public function behaviors()// Prior to action Execute , Can be used to implement page caching 
  {
    return [
      [
        'class'=>'yii\filters\HttpCache',// Full page cache 
        'lastModified'=>function(){
          return filemtime('hw.txt');
          //return 22221231231231;// You can record the data in the cache and read it from the cache every time you modify it 
        },
        'etagSeed'=>function(){
          $fp = fopen('hw.txt','r');//hw.txt In web Under the root directory of 
          $title = fgets($fp);// Read the 1 Row 
          fclose($fp);
          return $title;
          //return 'etagseed2123123';// Content 
        },
      ]
    ];
  }
  public function actionIndex()
  {
    $content = file_get_contents('hw.txt');
    return $this->renderPartial("index",['new'=>$content]);
  }
}

httpcache/index.php


<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 20:19
 */
?>
<div>
  <div> This is http Cache page </div>
  <p><?= $new;?></p>
</div>

More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to PHP programming based on Yii framework.


Related articles: