- FuelPHP 教程
- FuelPHP - 首頁
- FuelPHP - 簡介
- FuelPHP - 安裝
- FuelPHP - 架構概述
- FuelPHP - 簡單 Web 應用
- FuelPHP - 配置
- FuelPHP - 控制器
- FuelPHP - 路由
- FuelPHP - 請求 & 響應
- FuelPHP - 檢視
- FuelPHP - 展示器
- FuelPHP - 模型 & 資料庫
- FuelPHP - 表單程式設計
- FuelPHP - 驗證
- 高階表單程式設計
- FuelPHP - 檔案上傳
- FuelPHP - Ajax
- FuelPHP - HMVC 請求
- FuelPHP - 主題
- FuelPHP - 模組
- FuelPHP - 包
- Cookie & Session 管理
- FuelPHP - 事件
- FuelPHP - 郵件管理
- FuelPHP - 分析器
- 錯誤處理 & 除錯
- FuelPHP - 單元測試
- 完整工作示例
- FuelPHP 有用資源
- FuelPHP - 快速指南
- FuelPHP - 有用資源
- FuelPHP - 討論
FuelPHP - 路由
路由將請求的 URI 對映到特定控制器的某個方法。在本節中,我們將詳細討論 FuelPHP 中路由的概念。
配置
路由配置檔案位於fuel/app/config/routes.php。預設的routes.php檔案定義如下:
<?php
return array (
'_root_' => 'welcome/index', // The default route
'_404_' => 'welcome/404', // The main 404 route
'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'),
);
這裡,_root_ 是預定義的預設路由,當應用程式以根路徑 / 訪問時(例如:https://:8080/)將匹配此路由。_root_的值是當它匹配時要解析的控制器和操作。welcome/index解析為Controller_Welcome控制器和action_index操作方法。類似地,我們還有以下保留路由。
root - 當未指定 URI 時,預設路由。
403 - 當找到 HttpNoAccessException 時丟擲。
404 - 當頁面未找到時返回。
500 - 當找到 HttpServerErrorException 時丟擲。
簡單路由
路由與請求 URI 進行比較。如果找到匹配項,則將請求路由到 URI。簡單路由描述如下:
return array ( 'about' => 'site/about', 'login' => 'employee/login', );
這裡,about 匹配 https://:8080/about 並解析控制器 Controller_Site 和操作方法 action_about
login 匹配 https://:8080/login 並解析控制器 Controller_Login 和操作方法 action_login
高階路由
您可以在路由中包含任何正則表示式。Fuel 支援以下高階路由功能:
:any - 從 URI 中的該點開始匹配任何內容,但不匹配“無”
:everything - 與 :any 類似,但還匹配“無”
:segment - 僅匹配 URI 中的 1 個段,但該段可以是任何內容
:num - 匹配任何數字
:alpha - 匹配任何字母字元,包括 UTF-8
:alnum - 匹配任何字母數字字元,包括 UTF-8
例如,以下路由匹配 URI https://:8080/hello/FuelPHP 並解析控制器 Controller_Welcome 和操作 action_hello
'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'),
Controller_Welcome 中對應的操作方法如下:
public function action_hello() {
$this->name = Request::active()->param('name', 'World');
$message = "Hello, " . $this->name;
echo $message;
}
這裡,我們使用了 Request 類從 URL 獲取 name 引數。如果未找到 name,則使用 World 作為預設值。我們將在請求和響應章節學習Request類。
結果
HTTP 方法操作
FuelPHP 支援路由以匹配 HTTP 方法字首操作。以下是基本語法。
class Controller_Employee extends Controller {
public function get_index() {
// called when the HTTP method is GET.
}
public function post_index(){
// called when the HTTP method is POST.
}
}
我們可以根據配置檔案中的 HTTP 動詞將 URL 路由到控制器和操作。
return array (
// Routes GET /employee to /employee/all and POST /employee to /employee/create
‘employee’ => array(array('GET', new Route(‘employee/all')), array('POST',
new Route(‘employee/create'))),
);