如何在Class Symfony中设置会话

时间:2017-09-24 03:35:24

标签: symfony

当用户登录和/或更新其语言环境时,此服务应更新会话区域设置:

当用户登录时(它将会话区域设置设置为用户区域设置)但当用户更新其区域设置(并且不注销)时,此服务很有效,会话区域设置不会更改。

我该怎么做?

这是我的服务:

se.locale.interactive_login_listener:
        class: SE\UserBundle\EventSubscriber\UserLocaleListener
        calls:
            - [ setSession, [ "@session" ] ]
        tags:
            - { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }
            - { name: doctrine.event_listener, event: preUpdate, method: setPersistLocaleForAuthenticatedUser }

我的课程:

class UserLocaleListener
{
    private $session;

    public function setSession(Session $session)
    {
        $this->session = $session;
    }

    public function setLocaleForAuthenticatedUser(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();

        if ($lang = $user->getLocale()) {
            $event->getRequest()->setLocale($lang);
            $this->session->set('_locale', $lang);
        }
    }

    public function setPersistLocaleForAuthenticatedUser(LifecycleEventArgs $args)
    {
        $user = $args->getObject();
        if (!$user instanceof User) {
            return;
        }
        $this->session->set('_locale', $user->getLocale());
    }
}

我的控制器:

public function testAction(Request $request)
    {
        $user=$this->getUser();
        dump($user->getLocale());//->en
        $user->setLocale('fr');
        $em->persist($user);
        $em->flush();
        dump($user->getLocale());//->fr
        dump($request->getLocale());//->en
    }

0 个答案:

没有答案