close/destroy 之前的 Yii2 会话事件
Yii2 session event before close/destroy
我想在每次用户会话因 任何 原因被销毁之前 运行 一些代码。我没有在官方文档中找到任何绑定到会话的事件。有没有人找到解决方法?
会话组件没有开箱即用的事件。
您可以通过覆盖核心 yii\web\Session
组件来解决此问题。
1) 覆盖 yii\web\Session
组件:
<?php
namespace app\components;
use yii\web\Session as BaseSession
class Session extends BaseSession
{
/**
* Event name for close event
*/
const EVENT_CLOSE = 'close';
/**
* @inheritdoc
*/
public function close()
{
$this->trigger(self::EVENT_CLOSE); // Triggering our custom event first;
parent::close(); // Calling parent implementation
}
}
2) 将自定义组件应用于应用程序配置:
'session' => [
'class' => 'app\components\Session' // Passing our custom component instead of core one
],
3) 使用可用方法之一附加处理程序:
use app\components\Session;
use yii\base\Event;
Event::on(Session::className(), Session::EVENT_OPEN, function ($event) {
// Insert your event processing code here
});
或者,您可以将处理程序指定为某些 class 的方法,检查 official docs。
作为此方法的替代方法,请查看此 extension。我个人没有测试过。我认为 Yii 的方法将通过添加和触发自定义事件来实现,如上所述。
我想在每次用户会话因 任何 原因被销毁之前 运行 一些代码。我没有在官方文档中找到任何绑定到会话的事件。有没有人找到解决方法?
会话组件没有开箱即用的事件。
您可以通过覆盖核心 yii\web\Session
组件来解决此问题。
1) 覆盖 yii\web\Session
组件:
<?php
namespace app\components;
use yii\web\Session as BaseSession
class Session extends BaseSession
{
/**
* Event name for close event
*/
const EVENT_CLOSE = 'close';
/**
* @inheritdoc
*/
public function close()
{
$this->trigger(self::EVENT_CLOSE); // Triggering our custom event first;
parent::close(); // Calling parent implementation
}
}
2) 将自定义组件应用于应用程序配置:
'session' => [
'class' => 'app\components\Session' // Passing our custom component instead of core one
],
3) 使用可用方法之一附加处理程序:
use app\components\Session;
use yii\base\Event;
Event::on(Session::className(), Session::EVENT_OPEN, function ($event) {
// Insert your event processing code here
});
或者,您可以将处理程序指定为某些 class 的方法,检查 official docs。
作为此方法的替代方法,请查看此 extension。我个人没有测试过。我认为 Yii 的方法将通过添加和触发自定义事件来实现,如上所述。