2012-05-13 99 views
1

首先,Kohana的文檔很糟糕,在人們去閱讀文檔之前,我已經閱讀了文檔,他們似乎沒什麼意義,即使複製和粘貼一些代碼也沒有爲文檔中的某些內容工作。Kohana 3.2 - 路由問題

考慮到這一點,我有一個路線,像這樣:

//(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我希望它的默認行動view<userid>中指定的用戶,但我似乎無法找到任何這樣做的方式。

我能做到這一點是這樣的:

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後。

回答

1

我會成立的路線是這樣的:

Route::set('profile', '<userid>(/<action>)(/)', array(
    "userid" => "[a-zA-Z0-9_]+", 
    "action" => "[a-zA-Z]+" 
))->defaults(array(
    'controller' => 'profile', 
    'action' => 'index' 
)) 

然後在控制器前()方法:

if(!in_array($this->request->_action, array('photos', 'blog', 'index')){ 
    $this->request->_action = 'view'; 
} 

或者somethig similiar,只是驗證控制器動作.. 。

編輯:

這也可以工作:

if(!is_callable(array($this, 'action_' . $this->request->_action))){ 
    $this->request->_action = 'view'; 
} 
+0

對不起,我不明白。回到什麼? –

+0

而不是使用數組,但忽略我...'in_array(「action _ {$ request - > _ action}」,get_class_methods($ this))' –

+0

如果我理解得很對,請參閱我的編輯。 –