我一直在尝试让Symfony使用用户的语言环境来处理请求,而不使用URL路径中的语言环境。
我遵循了许多SO答案,这篇食谱文章让我走得很远。
我在登录事件上获取用户的语言首选项并将其设置到会话中。然后对于每个请求,我都有以下事件侦听器:
<?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)),
);
}
}
当我在列表器中回显语言环境时,我得到"sv",根据用户的偏好是正确的。但是当我echo $this->getRequest()->getLocale();
控制器时,它又是"fi",这是我在配置和其他地方的首选语言。会话密钥_locale
是控制器中的"sv"。
我将如何在控制器和树枝中正确基于会话的请求?
这里的解决方案有效:通过GET参数在Symfony中设置语言环境
因此,该服务还需要注入翻译器服务,然后应调用翻译器的->setLocale
来设置区域设置。