如何在Slim中构建可选参数作为问号?

Rap*_*ael 5 php api rest slim

我已经构建了我的第一个RESTful API并使用Slim作为我的框架.到目前为止它运作良好.

现在我已经看到一个很棒的API设计指南,它解释了,构建API的最佳方法是保持水平不变.我想这样做,并试图找出如何构建这样的URI:

my-domain.int/groups/search?q=my_query
Run Code Online (Sandbox Code Playgroud)

/ groups部分已经可以使用GET,POST,PUT,DELETE,搜索查询也可以这样工作:

my-domain.int/groups/search/my_query
Run Code Online (Sandbox Code Playgroud)

这是我在PHP中用于路由的代码:

$app->get('/groups/search/:query', 'findByName');
Run Code Online (Sandbox Code Playgroud)

我只是无法弄清楚如何在Slim中使用问号构建可选参数.我无法在谷歌上找到任何东西.

编辑:由于搜索似乎不适合我的场景我试图展示我想要实现的另一种方式:

假设我想从API获得部分响应.请求应如下所示:

my-domain.int/groups?fields=name,description
Run Code Online (Sandbox Code Playgroud)

不是这样的:

my-domain.int/groups/fields/name/description
Run Code Online (Sandbox Code Playgroud)

我怎么在路由中意识到这一点?

TPe*_*ete 6

查询字符串提供的参数GET参数不必在route参数中指定.框架将尝试匹配没有这些值的URI.要访问GET参数,您可以使用标准的 php方法,即使用超全局$ _GET:

$app->get('/groups/test/', function() use ($app) {
    if (isset($_GET['fields']){
        $test = $_GET('fields');
        echo "This is a GET route with $test";
    }
});
Run Code Online (Sandbox Code Playgroud)

或者你可以使用框架的方法,正如@Raphael在他的回答中提到的那样:

$app->get('/groups/test/', function() use ($app) {
    $test = $app->request()->get('fields');
    echo "This is a GET route with $test";
});
Run Code Online (Sandbox Code Playgroud)