通常, FOSUserBundle的实现通常很简单, 并且可以解决几乎所有需求。但是, 有些特殊任务可能很难在官方文档中找到, 或者不容易理解。这些任务之一是在用户成功启动会话(登录到你的应用程序)之后执行某项操作, 并且你需要知道用户何时执行此操作才能执行其他操作(根据电子邮件等在会话中添加参数) 。
你可以轻松地替换”事件监听器”, 以修改捆绑包(供应商目录)中的代码, 但是不建议这样做, 因为这是一种不好的做法, 并且你的更改将在任何更新中丢失, 因此建议改为添加登录事件监听器。
在本文中, 你将学习如何在用户成功登录到你的应用程序时专门监听登录事件。
实现
推荐的方法是在捆绑包中创建一个名为Listeners的文件夹, 并在其中使用以下代码创建一个名为LoginListener的类:
注意:不要忘记根据包的名称和类的位置更改类的名称空间。
<?php
// Change the namespace according to the location of this class in your bundle
namespace myBundle\Listeners;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class LoginListener {
protected $userManager;
public function __construct(UserManagerInterface $userManager){
$this->userManager = $userManager;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
// In order to test if it works, create a file with the name login.txt in the /web path of your project
$myfile = fopen("login.txt", "w");
fwrite($myfile, 'onSecurityInteractiveLogin succesfully executed !');
fclose($myfile);
// do something else
// return new Response();
}
}
现在你已经有了处理事件的类, 你需要在项目的services.yml文件中将其注册为服务:
services:
login_listener:
# path of the previously created class
class: myBundle\Listeners\LoginListener
arguments:
userManager: "@fos_user.user_manager"
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }
最后, 请记住清除缓存(手动或使用命令)并继续登录到你的项目。如本例所示, 将在项目的Web目录中创建文件(” login.txt”)仅用于测试目的, 可以随时更改该文件以用于响应或你需要执行的任何操作。
玩得开心 !
评论前必须登录!
注册