我正在关注this guide使用Slim Groups来版本化我的API。我只是想知道是否有可能针对旧版本捕获所有调用,而无需为每个函数执行此操作。就像通配符一样,你知道吗?
E.g。我从v1更新到v2,因此调用:myapi.com/v1/user/1
应该返回:您使用的是旧的API版本。
但我不想这样做(对于每个功能):
$app->group('/v1', function () use ($app) {
$app->group('/user', function () use ($app) {
$app->get('/:id', function ($id) {
echo "You are using an old version.";
});
});
});
但更像是这样(他忽略了所有子部分和参数):
$app->get('/v1/*', function ($id) {
echo "You are using an old version.";
});
这只是一个私有API,只有我的应用程序知道如何处理这个将使用所以请不要关心向后兼容性^^
答案 0 :(得分:1)
如果您只想返回任何/v1/anything/can/be/here
路由的消息,那么您可以使用通配符路由(docs)。
$app->get('/v1/:anything+', function () use ($app) {
$app->halt(400, 'You are using old API');
});
如果您希望保持旧API仍然有效,但想要修改响应以包含该消息,请使用组中间件。
<?php
$app->group('/v1', function () use $(app) {
// this is the middleware
echo 'You are using old API';
// $app->stop(); // uncomment to stop HERE
}, function () use ($app) {
$app->get('/:id', function ($id) {
// logic for the route
});
});
答案 1 :(得分:0)
我用过:
$app->group('/v1', function() {
$this->any('', function ($request, $response, $args) {
return $response->withJson(
array("error" => TRUE, "msg" => "You are using old API"),
400 // status code
);
});
});