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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10455336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:11:32  来源:igfitidea点击:

How do I obtain all the GET parameters on Silex?

phpsymfonysilex

提问by fesja

I've been using Silex for a day, and I have the first "stupid" question. If I have:

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

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

I want to get all the parameters (city_id) included in the middleware:

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

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

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

    ....
}

So, how do I get city_id (both the parameter name and its value) inside the middleware. I'm going to have like 30 actions, so I need something usable and maintainable.

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

What am I missing?

我错过了什么?

thanks a lot!

多谢!

Solution

解决方案

We need to get those extra parameters of $request->attributes

我们需要获取$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

    ...

});

回答by Jakub Zalas

In Requestobject you have access to multiple parameter bags, in particular:

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

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

$request->querycontains GET parameters only. city_idis not a GET parameter. It's an attribute parsed from the PATH_INFO.

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

Silex uses several Symfony Components. Request and Response classes are part of the HttpFoundation. Learn more about it from Symfony docs:

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