简体   繁体   中英

How to set the locale with symfony 3.4

How can I change the locale using symfony 3.4 (php)?

I have the locale saved for each user in my database. Now on this page they explain that you should create an event listener to set the locale. But they only provide a method - in which class do I put this method and how do I wire it up using my services.yml?

And if I'm in the service - how can I access my user object to actually get the locale I want to set?

Here is an example provided by the docs on how to create an kernel request listener .

In this listener you inject the TokenStorage serivce, which then provides you the current token and with it the attached user that is currently logged in. Then you take the locale from the user and set it to the request.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class RequestListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        $request = $event->getRequest();
        $request->setLocale($user->getLocale());
    }  
}

To understand, why Symfony requires the type-hint of an interface instead of an class please read the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM