更好的解决方案不是将要求放在所有路由或全局范围内,而是使用 EventListener 并将用户重定向到同一路由,但使用受支持的语言环境,例如:
<?php
namespace Selly\WebappLandingBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleInParamListener implements EventSubscriberInterface
{
/**
* @var Symfony\Component\Routing\RouterInterface
*/
private $router;
/**
* @var string
*/
private $defaultLocale;
/**
* @var array
*/
private $supportedLocales;
/**
* @var string
*/
private $localeRouteParam;
public function __construct(RouterInterface $router, $defaultLocale = 'en_US', array $supportedLocales = array('en_US'), $localeRouteParam = '_locale')
{
$this->router = $router;
$this->defaultLocale = $defaultLocale;
$this->supportedLocales = $supportedLocales;
$this->localeRouteParam = $localeRouteParam;
}
public function isLocaleSupported($locale) {
return in_array($locale, $this->supportedLocales);
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$locale = $request->get($this->localeRouteParam);
if(null !== $locale) {
$routeName = $request->get('_route');
if(!$this->isLocaleSupported($locale)) {
$routeParams = $request->get('_route_params');
if (!$this->isLocaleSupported($this->defaultLocale))
throw \Exception("Default locale is not supported.");
$routeParams[$this->localeRouteParam] = $this->defaultLocale;
$url = $this->router->generate($routeName, $routeParams);
$event->setResponse(new RedirectResponse($url));
}
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
和services.yml
services:
selly_webapp_landing.listeners.localeInParam_listener:
class: Selly\WebappLandingBundle\EventListener\LocaleInParamListener
arguments: [@router, "%kernel.default_locale%", "%locale_supported%"]
tags:
- { name: kernel.event_subscriber }
您parameters.yml
可以指定支持的语言环境:
locale_supported: ['en_US', 'pl_PL']