CodeIgniter has a very powerful routing feature that I’ve been using quite extensively lately. Consider a scenario where you may want to serve pages that will be requested by numeric id or a textual tag. For example http://yoursite.com/post/20 or http://yoursite.com/post/some-name – as you can see the URL structure is the same, but with regular expressions we can easily determine that in first case the value is numeric and in second it’s mixed. So based on the above information we can set up routing in the following way:

$route['post/([\\w]*)'] = 'post/getPostByName/$1';
$route['post/([0-9]*)'] = 'post/getPostById/$1';

The related controller methods should look something like this:

//will execute if 3rd segment is a string
public function getPostByName(){
	echo 'Name - '.$this->uri->rsegment(3);
}

//will execute if 3rd segment is numeric
public function getPostById(){
	echo 'Id - '.$this->uri->rsegment(3);
}

One thing to keep in mind is that routed segments should be accessed through $this->uri->rsegment() instead of the usual $this->uri->segment().

Because URI segments (the 2nd segment in this case) are mapped directly to controller method names, you can’t really use segments with dashes in them, and underscores don’t look as nice in URLs. Again, this can be easily overcome by setting up custom routes, like so:

$route['([\\w]*)-([\\w]*)/([\\w]*)'] = "post/$1_$2/$3";

The related controller methods should look something like this:

//will be called when the following URI is requested - http://yoursite.com/post-name/name
public function post_name(){
	//will print the actual route segments
	echo $this->uri->rsegment(3);
	echo $this->uri->rsegment(2);

	//will print segments seen in the browser address bar
	echo $this->uri->segment(2);
	echo $this->uri->segment(3);
}

There are many other possibilities, of course - you can read more about CI routing from the official documentation.


Comments are closed.