Codeigniter routing and REST server

gregory picture gregory · Feb 5, 2013 · Viewed 12.8k times · Source

I'm trying to achieve the following URLs for my API (I'm using Codeigniter and Phil Sturgeon's REST server library):

/players            -> refers to index method in the players controller
/players/rookies    -> refers to rookies method in the players controller

I don't want the URL to have a trailing "index"

/players/index

This is no problem at all when I define the routes like so:

$route['players'] = 'players/index';

Everything works as expected.

My problem is that I need additional URL segments like so:

/players/rookies/limit/10/offset/5/key/abcdef

The above example works, but the following does not:

/players/limit/10/offset/5/key/abcdef

I'm getting the following error: {"status":false,"error":"Unknown method."} Obviously there is no limit method in my controller.

How do I have to setup my routes.php config file to get these URLs to work properly?

Any help is much appreciated!

Answer

Philip picture Philip · Feb 5, 2013
//www.mysite.com/players
$route['players'] = 'players/index_get';//initial call to players index

//www.mysite.com/players/rookies
/** overrides the above **/
$route['players/(:any)'] = 'players/index_get/$1';//Changing defaults index

//www.mysite.com/players/rookies/10/4
/** overrides the above **/
$route['players/(:any)/(:num)/(:num)'] = 'players/index_get/$1/$2/$3';//Changing type,limit,offset

//All routes that are similar, like above that follow the previous, override the preceding one. 


//www.mysite.com/players/create
//overrides $route['players/(:any)']
$route['players/create'] = 'players/index_post';


class Players extends REST_Controller
{
    public $player_types = array();

    public function __construct(){
       $this->player_types = array(
          'rookies', 'seniors'
       );//manual assign or pull from db
    }
    /**
     * Index
     * $_GET
    **/
    public function index_get($type='rookies',$offset=0, $limit=0)//some defaults to show on initial call
    {
        // www.mysite.com/players/rookies
        // $route['players/(:any)'] = 'players/index_get/$1';
        // First uri segment, check to see if its a valid player 'type'

        if(!in_array(strtolower($type), $this->player_types)){
             //redirect ?
             return;
        }
    }
    /**
     * Index
     * $_POST
    **/
    public function index_post()
    {
        // Create a new player
    }
}