使用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()
函数永远不会在用户登录时执行。
我该如何做?
答案 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();