完成基本配置後,即可訪問應用預設首頁。進入專案目錄,使用 PHP 內建伺服器啟動:
php -S localhost:8999
瀏覽器輸入 localhost:8999 即見 ThinkPHP 預設笑臉首頁。此時訪問的是預設入口文件 index.php,即 IndexController 的 index() 方法,因預設配置:
'DEFAULT_CONTROLLER' => 'Index'
使用路由前需確保:
'URL_ROUTER_ON' => true這兩項在 ThinkPHP/Conf/convention.php 可找到。滿足條件後,在配置文件用 URL_ROUTE_RULES 陣列配置路由規則,格式:'路由表達式'=>'路由地址和傳入參數'。ThinkPHP 按定義順序匹配,一旦匹配即定位執行,後續規則不再匹配。
'URL_ROUTE_RULES'=>array(
'blogs/:year/:month/:day' => array('Index/archive', 'status=1'),
'blogs/:id' => 'Index/read',
),
表達式中 : 後為參數名(:year, :month, :id)。以 :id 為例,指向 Index 控制器 read 方法,接受 $id 參數:
public function read($id){ echo "read page with" .$id; }
瀏覽器輸入 https://localhost:8999/index.php/Home/blogs/2 輸出 read page with 2。Home 為預設模組('DEFAULT_MODULE' => 'Home')。
額外參數如第一條規則 array('Index/archive', 'status=1') 中的 status=1 同理傳入。
限制 :id 為整數:
'blogs/:id\d' => 'Index/read',
\d 表示僅匹配數字。若輸入 https://localhost:8999/index.php/Home/blogs/string 則不匹配此規則。
用 [] 包裹表示可選:
'blogs/:year/:month/[:day]' => array('Index/archive', 'status=1'),
day 現為可選參數,可傳可不傳。
常用於 .html、.htm 等後綴:
'blogs/:id' => array('Index/read',array('ext'=>'html'))
此規則僅在 .html 後綴生效。
正則路由表達式必須以 / 開頭,否則視為規則路由。錯誤寫法:
'#^blog\/(\d+)$#' => 'Index/read' // 非正則路由
正確寫法:
'/^new\/(\d{4})\/(\d{2})$/' => 'Index/achive?year=:1&month=:2',
正則子模式(如 \d{4}, \d{2})在路由地址中用 :1, :2 引用,序號對應子模式順序。
靜態路由為規則路由的靜態簡化版,不含動態參數,無需遍歷規則直接定位,效率較高。使用 URL_MAP_RULES 定義:
'URL_ROUTER_ON' => true,
'URL_MAP_RULES'=>array(
'new/top' => 'Index/top?type=top'
)
需在 Index 控制器建立 top() 方法。訪問 https://localhost:8999/index.php/Home/new/top 實際映射至 https://localhost:8999/index.php/Home/index/top/type/top。靜態路由為完整匹配,訪問 https://localhost:8999/index.php/Home/new/top/var/test 不會匹配。