我的网站有三种不同的翻译,默认情况下是英文,每个翻译都放在他自己的子域下。我想要做的是从子域 de.mydomain.com 重定向到 mydomain.com 并在名为“locale”的会话变量中设置翻译的语言,但问题是重定向后这个会话的变量消失了
配置.yml
framework:
session:
lifetime: 3600
cookie_domain: .mydomain
子域监听器:
class SubdomainListener
{
protected $domain;
/* @var Translator */
protected $translator;
/* @var Router */
protected $router;
public function __construct($domain, $translator, $router)
{
$this->domain = $domain;
$this->translator = $translator;
$this->router = $router;
}
public function onDomainParse(GetResponseEvent $event)
{
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
// don't do anything if it's not the master request
return;
}
/* @var $request Request */
$request = $event->getRequest();
/* @var $session Session */
$session = $request->getSession();
$host = $request->getHost();
$subDomain = str_replace($this->domain, '', $host);
$supportedTranslations = array('pl_PL', 'en_US', 'de_DE');
$preferredLanguage = $request->getPreferredLanguage();
if (!in_array($preferredLanguage, $supportedTranslations)) {
$preferredLanguage = 'en_US';
}
if (strlen($subDomain) > 0) {
if ($subDomain == "pl.") {
$preferredLanguage = "pl_PL";
} elseif ($subDomain == "en.") {
$preferredLanguage = "en_US";
} elseif ($subDomain == "de.") {
$preferredLanguage = "de_DE";
}
$route = $request->get('_route');
$routeParams = $request->get('_route_params');
if (strpos($route, '_sd') === false) {
$route = $route . '_sd';
}
$url = $this->router->generate($route, $routeParams);
$session->set('redirected', 1);
$session->set('locale', $preferredLanguage);
$this->translator->setLocale($preferredLanguage);
$event->setResponse(new RedirectResponse($url, 301));
}
if (!$session->get('redirected')) {
$session->set('locale', $preferredLanguage);
$this->translator->setLocale($preferredLanguage);
}
}
}