如何在 Laravel 4 中组织不同版本的 REST API 控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16501010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to organize different versioned REST API controllers in Laravel 4?
提问by Sherzod
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.
我知道有一种方法可以为带有路由的 REST API 创建版本化 URL,但是组织控制器和控制器文件的最佳方法是什么?我希望能够创建新版本的 API,并至少让旧版本继续运行一段时间。
回答by Travis Miller
I ended up using namespaces and directories under app/controllers:
我最终使用了 app/controllers 下的命名空间和目录:
/app
/controllers
/Api
/v1
/UserController.php
/v2
/UserController.php
And in UserController.php files I set the namespace accordingly:
在 UserController.php 文件中,我相应地设置了命名空间:
namespace Api\v1;
or
或者
namespace Api\v2;
Then in my routes I did something like this:
然后在我的路线中,我做了这样的事情:
Route::group(['prefix' => 'api/v1'], function () {
Route::get('user', 'Api\v1\UserController@index');
Route::get('user/{id}', 'Api\v1\UserController@show');
});
Route::group(['prefix' => 'api/v2'], function () {
Route::get('user', 'Api\v2\UserController@index');
Route::get('user/{id}', 'Api\v2\UserController@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.
我不肯定这是最好的解决方案。但是,它允许以不相互干扰的方式对控制器进行版本控制。如果需要,您可能可以做一些与模型类似的验证。