RESTful CodeIgniter Routes
Friday, April 15, 2011 at 2:43PM I love Ruby on Rails’ resourceful routing patterns. The ability to map specific HTTP verbs to actions is a beautifully clean way of implementing a common RESTful pattern.
While it would be difficult and counterintuitive to re-implement Rails’ router in PHP, we can use CodeIgniter’s routing system to good effect and get some similar RESTful route patterns.
/* --------------------------------------------------------------
* PRODUCTS
* ------------------------------------------------------------ */
$route['products'] = ($_SERVER['REQUEST_METHOD'] == 'GET') ? 'products/get_index' : 'products/post_create';
$route['products/new'] = 'products/get_new';
$route['products/(:any)'] = ($_SERVER['REQUEST_METHOD'] == 'GET') ? 'products/get_show/$1' : 'products/post_update/$1';
$route['products/(:any)/edit'] = 'products/get_edit/$1';
$route['products/(:any)/confirm_delete'] = 'products/post_confirm_delete/$1';
$route['products/(:any)/delete'] = 'products/post_delete/$1';
This will give us the following URL to controller function mappings:
GET /products -> get_index
GET /products/new -> get_new
GET /products/1 -> get_show(1)
GET /products/1/edit -> get_edit(1)
POST /products -> post_create
POST /products/1 -> post_update(1)
POST /products/1/confirm_delete -> post_confirm_delete(1)
POST /products/1/delete -> post_delete(1)
The beauty of this is that not only do you get a common URL pattern, but the method names match up with both functionality and HTTP method.
This isn’t entirely RESTful; if we were building a properly RESTful API we’d be using the PUT and DELETE methods instead. When you’re doing something like this, Phil Sturgeon’s REST Controller is your best bet.
For simple RESTful solutions, I absolutely love this reusable snippet of routing code.
codeigniter,
rest 
Reader Comments (2)
Thanks for this. I was just coming around to thinking that RoR actions (index, new, show, edit, etc) are going to be the best way to organize a site I am working on, but I hadn't yet got round to sorting out how to do the routing.
I realise this post was published 6 months ago but Mark Huot posted a similar solution on The Nerdary Blog, using the _remap() method, http://thenerdary.net/articles/entry/extending_codeigniters_controller, might be useful to someone who stumbles across this post.