Symfony2:与Request对象类似的Referrer对象?

时间:2011-08-17 06:55:46

标签: php localization symfony

我正在努力找到一个“引用者”对象供我使用 控制器。我预计会有一个类似于请求的对象 参数指定_controller,_route和 参数。

我要做的是重定向的语言切换器操作 用户到新语言的同一页面。沿途的东西 以下几行:

public function switchLangAction($_locale)
{
    $args = array();
    $newLang = ($_locale == 'en') ? 'fr' : 'en';

    // this is how I would have hoped to get a reference to the referrer request.
    $referrer = $this->get('referrer');
    $referrerRoute = $referrer->parameters->get('_route');
    $args = $referrer->parameters->get('args'); // not sure how to get the route args out of the params either!
    $args['_locale'] = $newLang;

    $response = new RedirectResponse( $this->generateUrl(
        $referrerRoute,
        $args
    ));

    return $response;
}

还有可能有另一种方法可以做到这一点 - 我知道 rails例如有“redirect_to:back”方法。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

为什么不在用户会话中更改语言环境?

首先,在路由器中定义您的语言环境

my_login_route:
    pattern: /lang/{_locale}
    defaults: { _controller: AcmeDemoBundle:Locale:changeLang }
    requirements:
        _locale: ^en|fr$

然后,设置会话

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LocaleController extends Controller
{
    public function switchLangAction($_locale, Request $request)
    {
        $session = $request->getSession();
        $session->setLocale($_locale);
        // ... some other possible actions

        return $this->redirect($session->get('referrer'));
    }
}

在所有其他控制器中,您应该通过调用

自行设置会话变量
$session->set('referrer', $request->getRequestUri());

您也可以使事件监听器自动为每个页面设置会话变量。

答案 1 :(得分:0)

这是我的控制者

  

类LocaleController扩展Controller {

public function indexAction()
{
    if(null === $this->getRequest()->getLocale()){
        $locale = $this->getRequest()->getPreferredLanguage($this->getLocales());
        $this->getRequest()->setLocale($locale);
    }
    else{
        $locale = $this->getRequest()->getLocale();
    }

    return $this->redirect($this->generateUrl('corebundle_main_index', array('_locale' => $locale)));
}

public function changeLocaleAction($_locale)
{
    $request = $this->getRequest();
    $referer = $request->headers->get('referer');
    $locales = implode('|',$this->getLocales());
    $url = preg_replace('/\/('.$locales.')\//', '/'.$_locale.'/', $referer, 1);
    return $this->redirect($url);
}

private function getLocales()
{
    return array('ru', 'uk', 'en');
}


/**
 * @Template()
 */
public function changeLocaleTemplateAction()
{
    return array();
}
     

}

相关问题