如何获取Silex上的所有GET参数?

fes*_*sja 28 php symfony silex

我一直在使用Silex一天,我有第一个"愚蠢"的问题.如果我有:

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

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

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

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

    ....
}
Run Code Online (Sandbox Code Playgroud)

那么,如何在中间件中获取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

    ...

});
Run Code Online (Sandbox Code Playgroud)

Jak*_*las 64

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

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

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

Silex使用了几个Symfony组件.请求和响应类是HttpFoundation的一部分.从Symfony docs了解更多信息:

  • 一句话.始终使用严格的比较器与strpos("!=="而不是"!=").记住比null和0与"="相比"相等"(但与===相比不相等). (3认同)