我希望web应用程序部分的URL结构如下:/user/FooBar42/edit/privacy
,我希望这路由到控制器:用户,功能:编辑,与FooBar42
和privacy
作为参数(按此顺序)。我应该如何完成这与CodeIgniter?
在application/config/routes.php
中定义此路由应该可以工作:
$route['user/(:any)/edit/(:any)'] = "user/edit/$1/$2";
但是,请注意上述路由中的(:any)
将匹配多个段。例如,user/one/two/edit/three
将调用user
控制器中的edit
函数,但只传递one
作为第一个参数,two
作为第二个参数。
用正则表达式([a-zA-Z0-9]+)
替换(:any)
将只允许一个长度至少为1的字母数字值。这缓解了上面的问题,其中/
将被允许允许多个段。现在,如果使用user/one/two/edit/three
,将显示404页面。
$route['user/([a-zA-Z0-9]+)/edit/([a-zA-Z0-9]+)'] = "user/edit/$1/$2";
您还可以使用CI控制器的重新映射选项
http://ellislab.com/codeigniter/user-guide/general/controllers.html重新映射
和这样做:
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);
}
}