Symfony2:成功登录事件后,执行一组操作 [英] Symfony2: After successful login event, perform set of actions

查看:96
本文介绍了Symfony2:成功登录事件后,执行一组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以将侦听器添加到security.interactive_login事件.

You can add a listener to the security.interactive_login event.

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

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

注意: :从Symfony 2.6开始不推荐使用SecurityContext.请参阅 http://symfony.com/blog/new-in -symfony-2-6-安全组件改进

Note: SecurityContext is deprecated as of Symfony 2.6. Please refer to 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);
   }

}

这篇关于Symfony2:成功登录事件后,执行一组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆