Question

I'm have built a CodeIgniter 2.0 site that provides an API. I'm now at the point where I need to create another version of the API that will not be backwards compatible with the previous version. Here's what I'm trying to do:

  1. Create versioned API controllers, something like {root}/application/controllers/api/v1.0/api.php and /v2.0/api.php, etc...
  2. Allow higher API versions to inherit from previous versions so I only have to override those methods that I want to

CodeIgniter doesn't seem to like this type of folder structure. And also, if all my API controllers have the same class name, I won't be able to subclass (i.e. "class API extends API" won't work). That said, I'd prefer to not have to do this: "class API2_0 extends API1_0", but I will if necessary.

I feel like URI Routing will be the key here (which I have limited grasp of), but if someone has already gong through this thought process, I'd very much appreciate some guidance. Thank you!!!

-Steve

Was it helpful?

Solution

Structure you API however you normally would as far as controllers and whatnot go, then just have:

application/controllers/api_1/foo.php
application/controllers/api_2/foo.php

Using Routes you can make that:

/api/1/foo
/api/2/foo

OTHER TIPS

I think you need improvement in your logic, please see this answer code igniter dynamic routing about adding custom routes to your site with which you can add your own. When it comes to controllers the best practice is to have one MY_Controller in your application/core/ folder that will be basic parent of all application controllers. Next, create new library in application/libraries/Apiv1_Controller.php that will extend MY_Controller class, please note that you will need __autoload() function to automatically load classes from application/libraries folder. Then all of your API Version 1 controllers will extend the Apiv1_Controller thus gaining access to its methods. For the version 2, just create another library Apiv2_Controller that extends Apiv1_Controller and controllers from version 2 will extend this class. This way your logic will remain in one class, so you don't have to create additional folders. Also with custom routes you can map your routes to the different controllers. Hope this helps for you.

//API V1 Controller
class Someapi extends Apiv1_Controller
{

}

//API V2 Controller
class Otherapi extends Apiv2_Controller
{

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top