【问题标题】:How to set the locale with symfony 3.4如何使用 symfony 3.4 设置语言环境
【发布时间】:2018-11-27 01:49:56
【问题描述】:

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

我为我的数据库中的每个用户保存了区域设置。现在在this page 上,他们解释说您应该创建一个事件侦听器来设置语言环境。但是他们只提供了一个方法——我把这个方法放在哪个类中,我如何使用我的 services.yml 来连接它?

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

【问题讨论】:

    标签: php symfony locale symfony-3.4


    【解决方案1】:

    这是example provided by the docs on how to create an kernel request listener

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

    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());
        }  
    }
    

    要理解,为什么 Symfony 需要接口的类型提示而不是类 please read the documentation

    【讨论】:

    • 使用您的代码我收到错误消息:无法自动装配服务“AppBundle\EventListener\LocaleListener”:方法“__construct()”的参数“$tokenStorage”引用类“Symfony\Component\Security\Core \Authentication\Token\Storage\TokenStorage”,但不存在这样的服务。尝试将类型提示更改为“Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface”。但是使用 TokenStorageInterface,我无法访问用户......有什么想法吗?
    • 对不起,我不明白。可以请你举个例子吗?
    • 建议的解决方案对我不起作用,所以我还不能接受它作为答案。如果我将TokenStorage 更改为TokenStorageInterfacegetToken() 方法需要一个参数,我不知道我应该在此处设置哪个参数。
    • 我使用的是\Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface,这就是问题所在。感谢您提供正确的界面 - 我这边的愚蠢错误。感谢您耐心地帮助我解决这个问题。它现在正在工作。
    • @MathiasBader 好吧,我明白了,这确实有些不同。很高兴能帮到你。
    猜你喜欢
    • 1970-01-01
    • 2012-12-25
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多