如何使用symfony 3.4设置语言环境 [英] How to set the locale with symfony 3.4

查看:47
本文介绍了如何使用symfony 3.4设置语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用symfony 3.4(php)更改语言环境?

我在我的数据库中为每个用户保存了语言环境.现在,在此页面上,他们解释说,您应该创建一个事件监听器来设置语言环境.但是他们只提供了一种方法-我将这种方法放在哪个类中,以及如何使用我的services.yml将其连接起来?

如果我在使用服务-如何访问用户对象以实际获取要设置的语言环境?

解决方案

这里是文档中提供的有关如何创建内核请求侦听器的示例.

在此侦听器中,您注入TokenStorage服务,然后为您提供当前令牌,并为您提供当前登录的附加用户.然后从该用户那里获取语言环境并将其设置为请求.

 使用Symfony \ Component \ Security \ Core \ Authentication \ Token \ Storage \ TokenStorageInterface;类RequestListener{私人$ tokenStorage;公共功能__construct(TokenStorageInterface $ tokenStorage){$ this-> tokenStorage = $ tokenStorage;}公共函数onKernelRequest(GetResponseEvent $ event){$user = $this->tokenStorage->getToken()->getUser();$ request = $ event-> getRequest();$ request-> setLocale($ user-> getLocale());}} 

要了解,为什么Symfony需要接口的类型提示而不是类请阅读文档.

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.

这篇关于如何使用symfony 3.4设置语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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