1
我跟着这个tutorial说明进行语言环境的变化“粘性”。setLocale的不工作的Symfony2应用
并创建了一个行动改变与用户请求的语言环境。
的LocaleListener类
<?php
namespace AppBundle\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 = 'en')
{
$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));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}
的目录结构:
服务
services:
app.locale_listener:
class: AppBundle\EventListener\LocaleListener
arguments: ['%kernel.default_locale%']
tags:
- { name: kernel.event_subscriber }
行动
/**
* @Route("/change-locale/{locale}", name="change_locale", defaults={"locale" = "it"})
*/
public function changeLocaleAction(Request $request) {
$request->setLocale('it');
$ref = $request->headers->get('referer');
return $this->redirect($ref);
}
但其没有工作,和我没有得到任何错误。为什么可能是这个问题?
了'locale'只是蛞蝓。 'setLocale'方法有问题。 – jihn
在这种情况下,您的语言环境侦听器非常无用。调用'setLocale()'方法后,你预期会发生什么? – xabbuh
因此,对于每个请求,我还应该发送'_locale'参数? – jihn