问题描述
这里是上下文:我有一个跨国家的网站,并且我的网址在法国和比利时的网站之间相同,但是我希望他们重定向到其他操作。 这是我的控制器的一个简单示例:
/**
* @Route({
* "fr": "/over-ons",* "be": "/about-us"
* },name="about_us")
*/
public function about()
{
die("about");
}
/**
* @Route({
* "fr": "/about-us",* "be": "/over-ons"
* },name="about_us_2")
*/
public function about2()
{
die("about 2");
}
然后,我创建了一个LocaleSubscriber(基于https://symfony.com/doc/current/session/locale_sticky_session.html):
<?PHP
namespace App\EventSubscriber;
use Symfony\Component\Eventdispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$this->defaultLocale = 'fr';
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$request->setDefaultLocale($this->defaultLocale);
$request->setLocale($this->defaultLocale);
$request->attributes->set('_locale',$this->defaultLocale);
$routeParams = $request->attributes->get('_route_params');
$routeParams['_locale'] = $this->defaultLocale;
$request->attributes->set('_route_params',$routeParams);
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest',20]],];
}
}
然后我打开http:// localhost / about-us,想看到消息“大约2”,但是我有“大约”。
因此,带有语言环境“ fr”的道路“ about-us”应与about2动作匹配,但它与about动作匹配。
请问您是否知道路由器是否可以将路由与特定区域设置相匹配?
感谢您的帮助!
解决方法
它不会那样工作。
路由器会将请求匹配到第一个匹配的路由。因此,此时与语言环境几乎没有关系。
请求来自/about-us
的路径,它与带有be
语言环境的about操作匹配,因为该路由是首先定义的。
如果要对多个语言环境使用相同的路由名称,则必须将语言环境添加到URL。子网域,前缀等并不重要。
例如:
fr/about-us
be/about-us
(当然,您不需要一一完成,将其定义为YAML中的前缀)