php Symfony2:成功登录事件后,执行一组操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11180351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:55:39  来源:igfitidea点击:

Symfony2: After successful login event, perform set of actions

phpsymfony

提问by jbsound

I need to perform a set of actions after a user successfully logs in. This includes loading data from the database and storing it in the session.

我需要在用户成功登录后执行一组操作。这包括从数据库加载数据并将其存储在会话中。

What is the best approach to implementing this?

实现这一点的最佳方法是什么?

回答by MDrollette

You can add a listener to the security.interactive_loginevent.

您可以向security.interactive_login事件添加侦听器。

attach your listener like so. In this example I also pass the security context and session as dependencies.

像这样附加你的听众。在此示例中,我还将安全上下文和会话作为依赖项传递。

Note:SecurityContext is deprecated as of Symfony 2.6. Please refer to http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

注意:SecurityContext 从 Symfony 2.6 开始被弃用。请参考 http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

parameters:
   # ...

   account.security_listener.class: Company\AccountBundle\Listener\SecurityListener

services:
   # ...

   account.security_listener:
        class: %account.security_listener.class%
        arguments: ['@security.context', '@session']
        tags:
            - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }

and in your listener you can store whatever you want on the session. In this case I set the users timezone.

在您的听众中,您可以在会话中存储您想要的任何内容。在这种情况下,我设置了用户时区。

<?php

namespace Company\AccountBundle\Listener;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class SecurityListener
{

   public function __construct(SecurityContextInterface $security, Session $session)
   {
      $this->security = $security;
      $this->session = $session;
   }

   public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
   {
        $timezone = $this->security->getToken()->getUser()->getTimezone();
        if (empty($timezone)) {
            $timezone = 'UTC';
        }
        $this->session->set('timezone', $timezone);
   }

}

回答by robinvdvleuten

You can even fetch the user instance from the event itself, no need to inject the token storage!

您甚至可以从事件本身获取用户实例,无需注入令牌存储!

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
    $event->getAuthenticationToken()->getUser()
}