苗条的可选路由参数后缀不起作用

slim optional route parameter suffix not working

我想定义一个最后有一个 .suffix 参数的路由。我想在我的应用程序中使用它来 return 满足用户的需求。例如 .json 或 .xml 或 none!。我应该如何定义我的路线?这是我想要的示例地址:

/user/all.json

/user/all.xml

/user/all # default json

这是我定义的路线。但它没有按预期工作。

/user/:method(\.(:type))

在 Slim 中,路线段由正斜杠定义,不能与点互换。但是,您可以在路由闭包中添加逻辑,也可以在多条路由中添加路由条件。

闭包中:

$app->get('/user/:methodtype', function ($methodtype) {
    if ($path = explode($methodtype, '.')) {
        if ($path[1] === 'json') {
            // Something to do with json...
        } elseif ($path[1] === 'xml') {
            // Something to do with xml...
        }
    }
});

或者使用路由条件,一一对应,这样它们就互斥了:

// JSON requests
$app->get('/user/:methodtype', function ($methodtype) {
    // Something to do with json...
})->conditions(array('methodtype' => '.json$'));

// XML requests
$app->get('/user/:methodtype', function ($methodtype) {
    // Something to do with xml...
})->conditions(array('methodtype' => '.xml$'));