在Yii中聆听注销事件2 [英] Listening for logout event in Yii 2

查看:118
本文介绍了在Yii中聆听注销事件2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道 Yii :: $ app-> user 在注销过程中触发这些事件。

So I know that Yii::$app->user triggers these events in the logout process.

const EVENT_BEFORE_LOGIN = 'beforeLogin';
const EVENT_AFTER_LOGIN = 'afterLogin';

但是,在每个请求开头添加一个监听器的正确位置在哪里?

But where is the right place to add a listener at the beginning of each request?

推荐答案

最好的地方是处理 yii / web / User ;通常,这是 common / models / User

The best place would be in the class which handles the identity of yii/web/User; usually, this is common/models/User.

在该类中,您可以进行以下初始化。 / p>

In that class, you can have the following initialization.

public function registerLogoutHook()
{
    $this->on(\yii\web\User::EVENT_AFTER_LOGOUT, function ($e) {
        Yii::$app->controller->goHome();
    });
}

您可以选择在网上注册此用户对象/ models / User]谁可以成功登录。逻辑可以如下

You may choose to register this on the web User object [of identity `common/models/User] who successfully logged in. The logic could be as follows

// [ ... omitted code ... ]
// $model is an instance of LoginForm
if ($model->load(Yii::$app->request->post()) && $model->login()) {
    Yii::$app->user->identity->registerLogoutHook();
    return $this->redirect(['customers/view', 'id' => Yii::$app->user->identity->id]);
}
// [ ... omitted code ... ]



编辑(:



另一种使现在工作的方法(yiisoft / yii2:2.0.7)是将事件处理程序添加到您的配置文件这样,所有处理程序都将在应用程序生命周期早期进行设置。

EDIT (:

Another way to get this working as of now ("yiisoft/yii2":"2.0.7") is to add the event handler to your config file. This way all handlers are setup early on in the application life cycle.

所以在你的 main.php 你将返回...

So in your main.php you would be returning...

[
    // ... some other things ...
    'components' => [
        // ... some other components ...
        'user' => [
            // ... some configuration for yii\web\User ...
            'on beforeLogout' => function ($e) {
                Yii::trace('Logout events are working!!!');
            },
            // ... more configurations for yii\web\User ...
        ],
        // ... some more components ...
    ],
    // ... some more things
]

对于处理程序,您可以使用回调,函数的名称或指定要调用的对象及其方法的数组。 这些注册事件的方法在这里列举< a>。

For the handler, you could either use a callback, the name of a function or an array specifying the object and its method to be called. These methods of registering an event are enumerated here.

beforeLogout 可以更改为 yii \\ \\web\User

这篇关于在Yii中聆听注销事件2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆