【问题标题】:Optional parameters in url - Slim 3url 中的可选参数 - Slim 3
【发布时间】:2016-09-11 03:54:46
【问题描述】:

我有一个非常简单的问题。我正在使用 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;

});

事实上后者并不能编译。

【问题讨论】:

  • 你能添加一个你想路由的路径的例子吗?

标签: php rest slim-3


【解决方案1】:

使用 unlimited Optional segments,意味着每个后续段都是保留的。

在您为/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);

});

更新:

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

$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");
    });

});

【讨论】:

  • 我需要一些东西来区分 /news[/{params:.*}]/details 和 /news[/{params:.*}]。我总是可以把它写成 /news/details[/{params:.*}] 但它不会再自我解释了......
  • 我明白了,我已经更新了答案,但实际上你的第一条路线确实符合两条路线,因为最后一段因为“/details”也符合你的第一条路线。
  • 你试过了吗?
  • 我刚刚再次更新了答案。它可能更接近您希望实现的目标。
  • 我会尝试这个版本,但我会把它给你。这不是我想要的,但这是一个很好的提示。
猜你喜欢
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多