Yii - 使用 Flash 資料



Yii 提供了一個 Flash 資料的概念。Flash 資料是一種會話資料,它:

  • 在一個請求中設定。
  • 僅在下一個請求中可用。
  • 之後將自動刪除。

步驟 1 - 向 SiteController 新增一個 actionShowFlash 方法。

public function actionShowFlash() {
   $session = Yii::$app->session;
   // set a flash message named as "greeting"
   $session->setFlash('greeting', 'Hello user!');
   return $this->render('showflash');
}

步驟 2 - 在 views/site 資料夾中,建立一個名為 showflash.php 的檢視檔案。

<?php
   use yii\bootstrap\Alert;
   echo Alert::widget([
      'options' => ['class' => 'alert-info'],
      'body' => Yii::$app->session->getFlash('greeting'),
   ]);
?>

步驟 3 - 當您在 Web 瀏覽器的位址列中輸入 https://:8080/index.php?r=site/show-flash 時,您將看到以下內容。

showflash php file

Yii 還提供以下會話類:

  • yii\web\CacheSession - 將會話資訊儲存在快取中。

  • yii\web\DbSession - 將會話資訊儲存在資料庫中。

  • yii\mongodb\Session - 將會話資訊儲存在 MongoDB 中。

  • yii\redis\Session - 使用 redis 資料庫儲存會話資訊。

廣告