Yii - 碎片快取



片段快取提供對網頁片段的快取。

步驟 1 − 向 SiteController 新增一個名為 actionFragmentCaching() 的新函式。

public function actionFragmentCaching() {
   $user = new MyUser();
   $user->name = "cached user name";
   $user->email = "cacheduseremail@gmail.com";
   $user->save();
   $models = MyUser::find()->all();
   return $this->render('cachedview', ['models' => $models]);
}

在上面的程式碼中,我們建立了一個新使用者並顯示了一個 cachedview 檢視檔案。

步驟 2 − 現在,在 views/site 資料夾中建立一個名為 cachedview.php 的新檔案。

<?php if ($this->beginCache('cachedview')) { ?>
   <?php foreach ($models as $model): ?>
      <?= $model->id; ?>
      <?= $model->name; ?>
      <?= $model->email; ?>
      <br/>
   <?php endforeach; ?>
<?php $this->endCache(); } ?>
<?php echo "Count:", \app\models\MyUser::find()->count(); ?>

我們將內容生成邏輯包含在一對 beginCache() 和 endCache() 方法中。如果快取中找到了內容,beginCache() 方法將渲染它。

步驟 3 − 轉到 URL https://:8080/index.php?r=site/fragment-caching 並重新載入頁面。輸出如下所示。

Fragment Caching

請注意,beginCache() 和 endCache() 方法之間的內容已快取。在資料庫中,我們有 13 個使用者,但只顯示了 12 個。

頁面快取

頁面快取提供對整個網頁內容的快取。頁面快取由 yii\filter\PageCache 支援。

步驟 1 − 修改 SiteController 的 behaviors() 函式。

public function behaviors() {
   return [
      'access' => [
         'class' => AccessControl::className(),
         'only' => ['logout'],
         'rules' => [
            [
               'actions' => ['logout'],
               'allow' => true,
               'roles' => ['@'],
            ],
         ],
      ],
      'verbs' => [
         'class' => VerbFilter::className(),
         'actions' => [
            'logout' => ['post'],
         ],
      ],
      [
         'class' => 'yii\filters\PageCache',
         'only' => ['index'],
         'duration' => 60
      ],
   ];
}

上面的程式碼將索引頁面快取 60 秒。

步驟 2 − 轉到 URL https://:8080/index.php?r=site/index。然後,修改索引檢視檔案的祝賀訊息。如果您重新載入頁面,您不會注意到任何更改,因為頁面已快取。等待一分鐘然後再次重新載入頁面。

Page Caching

HTTP 快取

Web 應用程式也可以使用客戶端快取。要使用它,您可以為控制器操作配置 yii\filter\HttpCache 過濾器。

Last-Modified 頭使用時間戳來指示頁面是否已被修改。

步驟 1 − 要啟用傳送 Last-Modified 頭,請配置 yii\filter\HttpCache::$lastModified 屬性。

public function behaviors() {
   return [
      [
         'class' => 'yii\filters\HttpCache',
         'only' => ['index'],
         'lastModified' => function ($action, $params) {
            $q = new \yii\db\Query();
            return $q->from('news')->max('created_at');
         },
      ],
   ];
}

在上面的程式碼中,我們僅為索引頁面啟用了 HTTP 快取。當瀏覽器第一次開啟索引頁面時,頁面將在伺服器端生成併發送到瀏覽器。第二次,如果沒有建立新聞,伺服器將不會重新生成頁面。

Etag 頭提供一個表示頁面內容的雜湊值。如果頁面更改,雜湊值也將更改。

步驟 2 − 要啟用傳送 Etag 頭,請配置 yii\filters\HttpCache::$etagSeed 屬性。

public function behaviors() {
   return [
      [
         'class' => 'yii\filters\HttpCache',
         'only' => ['index'],
         'etagSeed' => function ($action, $params) {
            $user = $this->findModel(\Yii::$app->request->get('id'));
            return serialize([$user->name, $user->email]);
         },
      ],
   ];
}

在上面的程式碼中,我們僅為 index 操作啟用了 HTTP 快取。它應該根據使用者的姓名和電子郵件生成 Etag HTTP 頭。當瀏覽器第一次開啟索引頁面時,頁面將在伺服器端生成併發送到瀏覽器。第二次,如果姓名或電子郵件沒有更改,伺服器將不會重新生成頁面。

廣告