My desired URL structure for a section of a web application is as follows:/user/FooBar42/edit/privacy
, and I would like this to route to controller: user, function: edit, with FooBar42
and privacy
as arguments (in that order). How should I accomplish this with CodeIgniter?
You can also use the remapping option of the CI controller
http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping
and doing something like this:
public function _remap($method, $params = array())
{
// check if the method exists
if (method_exists($this, $method))
{
// run the method
return call_user_func_array(array($this, $method), $params);
}
else
{
// method does not exists so you can call nay other method you want
$this->edit($params);
}
}
Defining this route in application/config/routes.php
should work:
$route['user/(:any)/edit/(:any)'] = "user/edit/$1/$2";
However, be aware that (:any)
in the above route would match multiple segments. For example, user/one/two/edit/three
would call the edit
function in the user
controller but only pass one
as the fist parameter and two
as the second.
Replacing the (:any)
with the regex ([a-zA-Z0-9]+)
will only allow one only alphanumeric values of length at least 1. This mitigates the issue above, where a /
would be permitted allowing multiple segments to be allowed. Now, if user/one/two/edit/three
was used, a 404 page would be shown.
$route['user/([a-zA-Z0-9]+)/edit/([a-zA-Z0-9]+)'] = "user/edit/$1/$2";