如何在 Laravel 4 中组织不同版本的 REST API 控制器?

2022-01-08 00:00:00 php laravel laravel-4

我知道有一种方法可以为带有路由的 REST API 创建版本化 URL,但是组织控制器和控制器文件的最佳方法是什么?我希望能够创建新版本的 API,并让旧版本至少运行一段时间.

I know there's a way to create versioned URLs for REST APIs with routes, but what's the best way to organize controllers and controller files? I want to be able to create new versions of APIs, and still keep the old ones running for at least some time.

推荐答案

我最终使用了 app/controllers 下的命名空间和目录:

I ended up using namespaces and directories under app/controllers:

/app
  /controllers
    /Api
      /v1
        /UserController.php
      /v2
        /UserController.php

在 UserController.php 文件中,我相应地设置了命名空间:

And in UserController.php files I set the namespace accordingly:

namespace Apiv1;

namespace Apiv2;

然后在我的路线中我做了这样的事情:

Then in my routes I did something like this:

Route::group(['prefix' => 'api/v1'], function () {
  Route::get('user',      'Apiv1UserController@index');
  Route::get('user/{id}', 'Apiv1UserController@show');
});

Route::group(['prefix' => 'api/v2'], function () {
  Route::get('user',      'Apiv2UserController@index');
  Route::get('user/{id}', 'Apiv2UserController@show');
});

我不肯定这是最好的解决方案.但是,它允许以不相互干扰的方式对控制器进行版本控制.如果需要,您可能可以对模型进行类似的验证.

I'm not positive this is the best solution. However, it has allowed versioning of the controllers in a way that they do not interfere with each other. You could probably do something verify similar with the models if needed.

相关文章