Kohana 3.x 路由系統採用「模式匹配 + 參數捕獲」機制,功能強大但文檔多為英文。本文針對 Kohana 3.1.0 穩定版,詳細解析 bootstrap.php 中的路由定義語法、預設路由結構、自定義多參數路由實作、參數獲取方式,並推薦優質學習資源。
Route::set('路由名稱', 'URL模式')
->defaults(array(
'controller' => '預設控制器',
'action' => '預設動作',
'參數名' => '預設值',
));
(/參數) 表示可選段,<參數> 表示必選段Route::set('default', '((/(/)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
解析:
/controller/action/id/controller → action=index/controller/action → id=null/ → controller=welcome, action=index重要: 每個路由必須指定預設 controller 和 action,否則會拋出異常。
URL 格式:/product/分類ID/頁碼,例如 /product/5/2 表示分類 5 的第 2 頁。
Route::set('product', 'product(/(/))')
->defaults(array(
'controller' => 'product',
'action' => 'index',
'id' => 0,
'page' => 1, // 注意:某些版本用 NULL 會報錯,建議給具體預設值
));
| URL | id | page | 說明 |
|---|---|---|---|
| /product | 0 | 1 | 使用全部預設值 |
| /product/5 | 5 | 1 | 指定分類,頁碼預設 |
| /product/5/2 | 5 | 2 | 完整指定 |
class Controller_Product extends Controller {
public function action_index() {
// 獲取路由參數 (注意:參數名必須與路由定義一致)
$id = $this->request->param('id'); // 分類 ID
$page = $this->request->param('page'); // 頁碼
// 業務邏輯...
$products = Model_Product::get_by_category($id, $page);
$this->response->body(View::factory('product/list')
->set('products', $products)
->set('category_id', $id)
->set('current_page', $page)
);
}
}
Route::set('article', 'article/', array('id' => '\d+'))
->defaults(array(
'controller' => 'article',
'action' => 'view',
));
僅匹配數字 ID,非數字自動 404。
// 靜態路由優先 (放在動態路由之前)
Route::set('admin_login', 'admin/login')
->defaults(array('controller' => 'admin', 'action' => 'login'));
// 動態路由次之
Route::set('admin', 'admin(/(/(/)))')
->defaults(array('controller' => 'dashboard', 'action' => 'index'));
// 在視圖或控制器中生成連結
echo Route::get('product')->uri(array(
'id' => 5,
'page' => 2,
)); // 輸出: /product/5/2
// 列出所有已註冊路由
var_dump(Route::all());
// 測試 URL 匹配結果
$route = Route::get('product');
var_dump($route->matches('/product/5/2')); // 回傳參數陣列或 false
建議對比閱讀兩份資源,官方查 API、Wiki 看範例,快速掌握 Kohana 3 路由精髓。
HTTP::redirect() 替代 Request::redirect()Route::cache() 加速生產環境掌握「模式定義 → 預設值 → 參數獲取 → 反向生成」四步驟,即可駕馭 Kohana 靈活強大的路由系統。