0

我有一个非常简单的问题。我正在使用 Slim 3 构建一个 RESTfull api。

这是怎么回事:

$app->get('/news[/{params:.*}]', function ($request, $response, $args) {
    $params = explode('/', $request->getAttribute('params'));
    $response->write("news!");
    return $response;

});

但不是这个:

$app->get('/news[/{params:.*}]/details', function ($request, $response, $args) {
$params = explode('/', $request->getAttribute('params'));
        $response->write("news details");
        return $response;

});

事实上后者不编译。

4

1 回答 1

7

使用无限制的 可选段意味着保留每个后续段。

在您为/news[/{params:.*}]以下路径定义的路线中符合条件:

/news
/news/foo
/news/foo/bar
/news/foo/bar/... 

/details因此,如果在方括号之后添加额外的固定段,则将不起作用。

当您将其定义为方括号内/news[/{params:.*}/details]/details段时,它确实适用于详细信息,但不能与第一条路线结合使用,并且会中断。您仍然可以使用您的第一条路线并检查最后一个参数,或者使用以下可选参数:

$app->get('/news[/{params:.*}[/details]]', function ($request, $response, $args) {

    $params = explode('/', $request->getAttribute('params'));

    if (end($params) != 'details') {

        $response->write("news!");

    } else {

        // $params for details;
        array_pop($params);

        $response->write("news details");
    }

    // $params is an array of all the optional segments
    var_dump($params);

});

更新:

这里的实际问题似乎是路线中的冲突定义,例如,无限的可选段将始终与第二个定义的路线匹配。可以通过使用路由正则表达式定义路由并将它们包含在非冲突匹配之前的路由组中来解决:

$app->group('/news', function () {

    $this->map(['GET'], '', function ($request, $response, $args) {

        $response->write("news w/o params");

    })->setName('news');

    // Unlimited optional parameters not ending with "/details"
    $this->get('/{params:[[:alnum:]\/]*[^\/details]}', function ($request, $response, $args) {
        $params = explode('/', $request->getAttribute('params'));

        var_dump($params);

        $response->write("news!");
    });

    // Unlimited optional parameters ending with "/details"
    $this->get('/{params:[[:alnum:]\/]*\/details}', function ($request, $response, $args) {
        $params = explode('/', $request->getAttribute('params'));
        array_pop($params); // fix $params

        var_dump($params);

        $response->write("news details");
    });

});
于 2016-09-13T17:29:18.070 回答