Symfony2:类似于请求对象的引用对象


Symfony2: Referrer object similar to Request object?

我试图没有运气找到一个"引用"对象在我的控制器。我预计会有一个与请求类似的对象对象,参数指定_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"方法。

为什么不在用户会话中更改区域设置呢?

首先,在router 中定义你的区域设置
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());

您还可以创建一个事件侦听器来自动为每个页面设置会话变量。

这是我的控制器

类LocaleController扩展控制器{

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

}