1

我想要一个解析并组合一组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 和重定向的信息?

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

4

1 回答 1

5

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

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

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

$url = $this->router->pathFor('search', [], $search_params);
于 2017-01-17T19:49:47.253 回答