编写此Symfony2 URL重定向的更好方法

时间:2013-03-18 12:43:34

标签: symfony

这很有效,但很麻烦。我一直在搞乱参数包,但没有什么比我的代码更好。

我只是想重定向到同一页面并删除查询字符串,但要比它更好地编码:

$r = $this->request;

$url = $r->getUri();

$replace = "abc=" . $r->query->get( 'abc' );
$url = str_replace("?".$replace, "?", $url);
$url = str_replace("&".$replace, "", $url);

$response = new RedirectResponse($url);
$this->event->setResponse($response);

1 个答案:

答案 0 :(得分:5)

删除整个查询字符串:

$response = new RedirectResponse($request->getPathInfo());

仅从查询字符串中删除参数:

$route  = $request->get('_route');
$params = array_merge(
    $request->get('_route_params'), 
    $request->query->all()
);

unset($params['param_to_remove']);
// or $params['param_to_remove'] = null;

$response = new RedirectResponse($this->router->generate($route, $params);