Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 811
Sherzod Avatar asked May 11 '13 19:05

Sherzod


1 Answers

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.

like image 82
Travis Miller Avatar answered Sep 21 '22 17:09

Travis Miller