Php 事件侦听器中的Symfony区域设置已更改,但控制器中的默认设置再次更改
我一直在尝试让Symfony在请求中使用用户的语言环境,而不使用URL路径中的语言环境 我已经找到了很多答案,并且走了很远 我在登录事件中获取用户的语言首选项,并将其设置到会话中。然后,对于每个请求,我都有一个事件侦听器:Php 事件侦听器中的Symfony区域设置已更改,但控制器中的默认设置再次更改,php,symfony,locale,Php,Symfony,Locale,我一直在尝试让Symfony在请求中使用用户的语言环境,而不使用URL路径中的语言环境 我已经找到了很多答案,并且走了很远 我在登录事件中获取用户的语言首选项,并将其设置到会话中。然后,对于每个请求,我都有一个事件侦听器: <?php namespace My\UserBundle\EventListener; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel
<?php
namespace My\UserBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'fi')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
#if ($locale = $request->attributes->get('_locale')) {
# $request->getSession()->set('_locale', $locale);
#} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
#}
echo $request->getLocale();
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
这里的解决方案有效:
因此,服务还需要注入translator服务,然后应该调用translator的->setLocale
来设置区域设置。可能重复的