【问题标题】:How do I obtain all the GET parameters on Silex?如何获取 Silex 上的所有 GET 参数?
【发布时间】:2012-05-04 19:57:18
【问题描述】:

我已经使用 Silex 一天了,我有第一个“愚蠢”的问题。如果我有:

$app->get('/cities/{city_id}.json', function(Request $request, $city_id) use($app) {
    ....
})
->bind('city')
->middleware($checkHash);

我想获取中间件中包含的所有参数(city_id):

$checkHash = function (Request $request) use ($app) {

    // not loading city_id, just the parameter after the ?
    $params = $request->query->all();

    ....
}

那么,我如何在中间件中获取 city_id(参数名称及其值)。我将有大约 30 个动作,所以我需要一些可用和可维护的东西。

我错过了什么?

非常感谢!

解决方案

我们需要获取那些$request->attributes

的额外参数
$checkHash = function (Request $request) use ($app) {

    // GET params
    $params = $request->query->all();

    // Params which are on the PATH_INFO
    foreach ( $request->attributes as $key => $val )
    {
        // on the attributes ParamaterBag there are other parameters
        // which start with a _parametername. We don't want them.
        if ( strpos($key, '_') != 0 )
        {
            $params[ $key ] = $val;
        }
    }

    // now we have all the parameters of the url on $params

    ...

});

【问题讨论】:

  • 看起来 ->middleware() 已经不存在了?

标签: php symfony silex


【解决方案1】:

Request 对象中,您可以访问多个参数包,特别是:

  • $request->query - GET 参数
  • $request->request - POST 参数
  • $request->attributes - 请求属性(包括从 PATH_INFO 解析的参数)

$request->query 仅包含 GET 参数。 city_id 不是 GET 参数。它是从 PATH_INFO 解析的属性。

Silex 使用多个Symfony Components。 Request 和 Response 类是 HttpFoundation 的一部分。从 Symfony 文档了解更多信息:

【讨论】:

  • 感谢 kuba,您为我指出了解决方案。我已将其添加到问题中。
  • 一句话。始终使用带有 strpos 的严格比较器(“!==”而不是“!=”)。请记住,与 == 相比,null 和 0 是“相等的”(但与 === 相比不相等)。
猜你喜欢
  • 2014-03-18
  • 2018-02-09
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
相关资源
最近更新 更多