Symfony2:重定向后丢失会话变量

时间:2013-05-11 15:27:15

标签: php symfony

我的网站有三种不同的翻译,默认情况下是英文,每个翻译都放在他自己的子域下。我正在尝试做的是从子域de.mydomain.com重定向到mydomain.com并在名为“locale”的会话变量中设置翻译的语言,但问题是重定向后此会话的变量消失

config.yml

framework:
    session:
        lifetime:       3600
        cookie_domain: .mydomain

SubdomainListener:

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);
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

这种“丢失”的原因可能是使用非域cookie。

要启用此功能,您应在配置中指定您的域。根据{{​​3}},对于Symfony的2.22.1版本:

framework:
    session:
        cookie_domain: .yoursite.com