[英]Kohana 3.2 - Routing questions
首先,Kohana的文档非常糟糕,在人们去“阅读文档”之前,我已经阅读了文档,而且似乎没有多大意义,即使复制和粘贴某些代码对于文档中的某些内容也不起作用。
考虑到这一点,我有一条这样的路线:
//(enables the user to view the profile / photos / blog, default is profile)
Route::set('profile', '<userid>(/<action>)(/)', array( // (/) for trailing slash
"userid" => "[a-zA-Z0-9_]+",
"action" => "(photos|blog)"
))->defaults(array(
'controller' => 'profile',
'action' => 'view'
))
这使我去http://example.com/username
和被带到用户的个人资料, http://example.com/username/photos
采取查看用户的照片和http://example.com/username/blog
以查看博客。
如果有人去http://example.com/username/something_else
我希望它默认为<userid>
指定的用户的操作view
,但我似乎找不到任何方法。
我可以这样做:
Route::set('profile', '<userid>(/<useraction>)(/)', array(
"userid" => "[a-zA-Z0-9_]+",
"useraction" => "(photos|blog)"
))->defaults(array(
'controller' => 'profile',
'action' => 'index'
))
然后在控制器中执行以下操作:
public function action_index(){
$method = $this->request->param('useraction');
if ($method && method_exists($this, "action_{$method}")) {
$this->{"action_{$method}"}();
} else if ($method) {
// redirect to remove erroneous method from url
} else {
$this->action_view(); // view profile
}
}
(在__construct()
函数中可能会更好,但是您可以理解它的要点。)
如果有更好的方法(我确实应该这样做),我宁愿不这样做。
我认为答案可能在正则表达式中,但以下操作无效:
$profile_functions = "blog|images";
//(enables the user to view the images / blog)
Route::set('profile', '<id>/<action>(/)', array(
"id" => "[a-zA-Z0-9_]+",
"action" => "($profile_functions)",
))->defaults(array(
'controller' => 'profile'
));
Route::set('profile_2', '<id>(<useraction>)', array(
"id" => "[a-zA-Z0-9_]+",
"useraction" => "(?!({$profile_functions}))",
))->defaults(array(
'controller' => 'profile',
'action' => 'view'
));
尽管ID后面没有任何内容时它确实匹配。
我将这样设置路线:
Route::set('profile', '<userid>(/<action>)(/)', array(
"userid" => "[a-zA-Z0-9_]+",
"action" => "[a-zA-Z]+"
))->defaults(array(
'controller' => 'profile',
'action' => 'index'
))
然后在控制器的before()方法中:
if(!in_array($this->request->_action, array('photos', 'blog', 'index')){
$this->request->_action = 'view';
}
或类似的东西,只需验证控制器中的动作即可。
编辑:
这也可以工作:
if(!is_callable(array($this, 'action_' . $this->request->_action))){
$this->request->_action = 'view';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.