I'm new to Codeigniter, and I'm trying to get accustomed to it by converting an old site into CI.
One thing I'm having trouble understand is the routing. If I don't want to have my url structure like /controller/method/id, I have to change it to something like $route['controller/(:num)'] = "controller/method/$1";
in routes.php. It just seems inefficient to me, is there something else I should be doing?
For example, on my site, the urls are /game/4242 and /player/SomeDude
Well, routing is effecient - the alternative is remapping your controllers.
Let's take a look at both possibilities.
An imaginary situtation:
At a later point, you'd like to allow your users to show badges/medals/achievements/something on their profile.
With routing, you can achieve it like this:
$route['player/(:any)/(:any)'] = "player/show_$2/$1";
$route['player/(:any)'] = "player/show_profile/$1";
And your controller could in turn look like this:
class Player extends CI_Controller
{
public function show_profile( $username )
{
// the profile info
}
public function show_badges( $username )
{
// the profiles badges
}
public function show_scores( $username )
{
// the profiles scores
}
}
}
Basically, this allows you to simply add another method in your controller prefixing the method with show_
(like public method show_friends( $username )
)and you can access it instantly by going to /player/SomeDude/friends
Looking at the alternative, remapping your controller would allow you not to use routes, but write a controller like this:
class Player extends CI_Controller
{
public function _remap($username, $params = array())
{
if(empty($username))
show_404();
$this->user = $this->user_model->find($username);
if(count($params) == 0)
$method = 'index';
else
$method = $params[0];
unset($params[0]); //No need to send the method along as a parameter
$method = 'process_'.$method;
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}
public method process_index()
{
// the profile info
}
public method process_badges()
{
// the profiles badges
}
public method process_scores()
{
// the profiles scores
}
}
Personally, I like routing. I think it's transparent and makes my controllers look cleaner.