通常, FOSUserBundle的实现通常很简单, 并且可以解决几乎所有需求。但是, 有些特殊任务可能很难在官方文档中找到, 或者不容易理解。这些任务之一是在用户成功启动会话(登录到你的应用程序)后执行某项操作, 你需要知道用户何时执行此操作才能执行其他操作(根据电子邮件等在会话中添加参数) 。
你可以轻松地替换”事件监听器”, 以修改捆绑包(供应商目录)中的代码, 但是不建议这样做, 因为这显然是一种不好的做法, 你的更改将在任何更新中丢失, 因此建议添加注销事件监听器。在本文中, 你将学习当用户成功从你的应用程序注销时如何专门监听注销事件。
实现
推荐的方法是在包中创建一个名称为Listeners的文件夹, 并在其中使用以下代码创建一个名称为LogoutListener的类:
注意:不要忘记根据包的名称和类的位置更改类的名称空间。
<?php
// LogoutListener.php - Change the namespace according to the location of this class in your bundle
namespace myBundle\Listeners;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
class LogoutListener implements LogoutHandlerInterface {
protected $userManager;
public function __construct(UserManagerInterface $userManager){
$this->userManager = $userManager;
}
public function logout(Request $Request, Response $Response, TokenInterface $Token) {
// ..
// Here goes the logic that you want to execute when the user logouts
// ..
// The following example will create the logout.txt file in the /web directory of your project
$myfile = fopen("logout.txt", "w");
fwrite($myfile, 'logout succesfully executed !');
fclose($myfile);
}
}
现在你有了一个处理注销事件的类, 我们需要创建一个将使用该事件的服务。继续修改项目的services.yml文件并注册新服务, 如下所示:
services:
# Register the LogoutListener service
# The namespace where the class is located
# and the class name at the end.
# we'll inject the user_manager in case that you need it
mybundle_logoutlistener:
class: myBundle\Listeners\LogoutListener
arguments:
userManager: "@fos_user.user_manager"
最后, 在这种情况下, 名称为mybundle_logoutlistener(显然可以自定义)的注册服务需要与security.yml文件中注销事件的处理程序一起使用:
security:
## ...
firewalls:
## ...
main:
## ...
logout:
handlers: [mybundle_logoutlistener]
你已经准备好出发了!请记住要清除缓存(手动或使用命令), 然后继续登录到你的项目然后注销。如本例所示, 将在项目的Web目录中创建一个文件(” logout.txt”)仅用于测试目的, 你可以根据需要进行更改。
编码愉快!
评论前必须登录!
注册