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 浏览器的地址栏中输入 http://localhost: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 数据库存储会话信息。

广告