【问题标题】:Slim Framework show info when using old api version使用旧 api 版本时 Slim 框架显示信息
【发布时间】:2016-01-18 14:37:26
【问题描述】:

我正在关注 this guide 使用 Slim Groups 来版本化我的 API。我只是想知道是否可以捕获针对旧版本的所有调用,而无需对每个函数都执行此操作。就像通配符一样,你知道吗?

例如我从 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,只有知道如何处理它的我的应用才会使用它,所以请不要关心向后兼容性 ^^

【问题讨论】:

    标签: slim


    【解决方案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
        });
    });
    

    【讨论】:

    • 天哪,这正是我要找的通配符 =) 没想到“+”会包括所有子路由 =) 谢谢!
    【解决方案2】:

    我用过:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      相关资源
      最近更新 更多