使用 GET 参数重定向到路由

Redirect to route with GET parameters

我想要一个解析 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 参数作为字符串附加到路由 URL:

// 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 和重定向的内容?

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

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

  1. 路线名称
  2. 路由模式占位符和替换值的关联数组
  3. 查询参数关联数组

您目前正在添加您的 q 参数作为路由占位符,如果您有类似这样的路由 /search/{q},那么它将起作用,因此要将其添加为查询参数,请使用第三个参数

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