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

Ale*_*nko 5 php localization symfony

我正在努力找到一个"引用者"对象,以便在我的控制器中使用.我希望有一个类似于请求对象的对象,其参数指定_controller,_route和arguments.

我想要做的是一个语言切换器操作,将用户重定向到新语言的同一页面.有点像:

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;
}
Run Code Online (Sandbox Code Playgroud)

也有可能有另一种方法来做到这一点 - 我知道在rails中有例如"redirect_to:back"方法.

任何帮助将不胜感激.

gil*_*den 4

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

首先,在路由器中定义您的区域设置

my_login_route:
    pattern: /lang/{_locale}
    defaults: { _controller: AcmeDemoBundle:Locale:changeLang }
    requirements:
        _locale: ^en|fr$
Run Code Online (Sandbox Code Playgroud)

然后,设置会话

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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

在所有其他控制器中,您应该通过调用自己设置会话变量

$session->set('referrer', $request->getRequestUri());
Run Code Online (Sandbox Code Playgroud)

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