Yii2-usuario:扩展登录过程

时间:2019-09-07 14:12:02

标签: php yii2 user-management

使用Yii2-usuario,我想通过在用户成功登录后设置一些会话变量来扩展登录过程。

我尝试通过以下方式扩展用户模型:

替换./config/web.php中的User类:

'modules' => [
    'user' => [
        'class' => Da\User\Module::class,
        'classMap' => [
            'User' => app\models\user\User::class,
        ],
    ],
],

并重载User中的./models/users/User.php类:

namespace app\models\user;
use Da\User\Model\User as BaseUser;

class User extends BaseUser
{
    public function login(IdentityInterface $identity, $duration = 0)
    {
        $ok = parent::login();
        myNewFeature();
        return $ok;
    }
}

docs中所述。

但是:此login()函数永远不会在用户登录时执行。

我该如何做?

1 个答案:

答案 0 :(得分:1)

最好的方法是利用扩展提供的事件。如果您查看FormEvents,则会在SecurityController标题

下看到以下内容
  • FormEvent::EVENT_BEFORE_LOGIN:在用户登录系统之前发生
  • FormEvent::EVENT_AFTER_LOGIN:在用户登录系统后发生

因此,您需要做的是定义一个事件并在其中添加代码,文档要求在events.php文件夹内创建一个名为config的文件,然后将其加载到输入脚本中。

以下是为SecurityController设置事件的示例:

<?php 
// events.php file

use Da\User\Controller\SecurityController;
use Da\User\Event\FormEvent;
use yii\base\Event;

Event::on(SecurityController::class, FormEvent::EVENT_AFTER_LOGIN, function (FormEvent $event) {
    $form = $event->getForm();

    // ... your logic here
});

最后一部分是在您的输入脚本中加载该文件

<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');

require(__DIR__ . '/../config/events.php'); // <--- adding events here! :)

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')
);

$application = new yii\web\Application($config);
$application->run();