使用GET参数重定向到路由

时间:2017-01-17 17:15:46

标签: php redirect routes slim slim-3

我想要一个解析并汇总一组GET参数的路由,以重定向到另一个需要GET参数的路由。

我原本希望这会有效,我将$search_params作为pathFor()方法的一部分传递给我:

// SEARCH VIEW
$app->get('/search', function ($request, $response, $args) {
    $api = $this->APIRequest->get($request->getAttribute('path'),$request->getQueryParams());
    $args['data'] = json_decode($api->getBody(), true);
    return $this->view->render($response, 'search.html.twig', $args);
})->setName('search');

// ADVANCED SEARCH VIEW
$app->get('/advanced_search', function ($request, $response, $args) {    
    return $this->view->render($response, 'advanced_search.html.twig', $args);
});

// ADVANCED SEARCH PROCESS
$app->post('/advanced_search', function ($request, $response, $args) {    

    // get settings
    $settings = $this->get('settings');

    // get post parameters
    $qp = $request->getParsedBody();

    // translate advanced search form parameters to Solr-ese
    $search_params = array();
    $search_params['q'] = $qp['query'];

    // redirect to GET:/search, with search parameters
    $url = $this->router->pathFor('search', $search_params);    
    return $response->withStatus(302)->withHeader('Location', $url);

});

但是这并没有将数组$search_params附加为GET参数。我理解,如果/search路由在URL中预期带有类似{q}之类的参数,则会被捕获,但我需要附加一组未知的GET参数。

我的解决方法是执行以下操作,手动使用http_build_query()GET参数作为字符串附加到路由网址:

// SEARCH VIEW
$app->get('/search', function ($request, $response, $args) {
    $api = $this->APIRequest->get($request->getAttribute('path'),$request->getQueryParams());
    $args['data'] = json_decode($api->getBody(), true);
    return $this->view->render($response, 'search.html.twig', $args);
})->setName('search');

// ADVANCED SEARCH VIEW
$app->get('/advanced_search', function ($request, $response, $args) {    
    return $this->view->render($response, 'advanced_search.html.twig', $args);
});

// ADVANCED SEARCH PROCESS
$app->post('/advanced_search', function ($request, $response, $args) {    

    // get settings
    $settings = $this->get('settings');

    // get post parameters
    $qp = $request->getParsedBody();

    // translate advanced search form parameters to Solr-ese
    $search_params = array();
    $search_params['q'] = $qp['query'];

    // redirect to GET:/search, with search parameters
    $url = $this->router->pathFor('search')."?".http_build_query($search_params);    
    return $response->withStatus(302)->withHeader('Location', $url);

});

但那感觉很笨拙。我错过了关于Slim 3和重定向的内容吗?

是否与重定向到POST路由的GET路由相关?我尝试在重定向中使用HTTP代码307作为withStatus(),但正如预期的那样,将方法请求更改为/search,这对我们的目的不起作用

1 个答案:

答案 0 :(得分:5)

你想在查询中添加q - param,路由器有3个参数:

  1. 路线名称
  2. 路由模式占位符和替换值的关联数组
  3. 查询参数的关联数组
  4. 您当前正在添加q - 参数作为路径占位符,如果您有类似路由/search/{q}的内容,则可以使用此参数,因此要将其添加为查询参数,请使用第3个参数

    $url = $this->router->pathFor('search', [], $search_params);