How to organize different versioned REST API controllers in Laravel 4?

你说的曾经没有我的故事 提交于 2019-12-18 10:13:59

问题


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.


回答1:


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

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

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

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.



来源:https://stackoverflow.com/questions/16501010/how-to-organize-different-versioned-rest-api-controllers-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!