Gene\Router 是 Gene 框架的核心元件之一,最大特色在於**極簡且強大的路由定義 DSL**:支援 RESTful 動詞、路徑參數、類別方法與閉包回呼、全域/區域鉤子、路由分組、快取機制等。
$router = new Gene\Router(); // 獨立使用需指定快取 key
$router = new Gene\Router('cacheKey'); // 區分不同路由配置
get/post/put/patch/delete/head/options/trace/connect// 1. 類別方法回呼:'Controller@method'
$router->get('/', 'Controllers_Index@index');
// 2. 閉包回呼
$router->get('/', function() { echo 'index'; });
// 3. 路徑參數(冒號前綴)
$router->get('/news/:id.html', function($params) {
echo 'id: ' . $params['id'];
});
// 4. 鉤子綁定:'localHook@globalHookAction'
$router->get('/admin/index', 'Admin@index', 'adminHook@clearAll');
// 定義全域前置鉤子
$router->hook('before', function() { echo 'before'; });
// 定義全域後置鉤子(接收路由參數)
$router->hook('after', function($params) { var_dump($params); });
// 定義區域鉤子(需在路由中聲明使用)
$router->hook('webCheck', function() {
session_start();
if (!isset($_SESSION['user']['user_id'])) {
header('Location: /login.html', 302);
die;
}
});
// 路由中排除全域鉤子:@clearBefore, @clearAfter, @clearAll
$router->group('/admin/user')
->get('/add', 'Admin_User@add', 'adminAuth@clearAll')
->post('/addPost', 'Admin_User@addPost', 'adminAuth@clearBefore')
->get('/edit/:id', 'Admin_User@edit', 'adminAuth@clearAll')
->group(); // 必須成對呼叫關閉分組
$router->error(401, function() { echo '401 Unauthorized'; });
$router->runError('401'); // 手動觸發
getTime():取得路由配置快取時間戳getTree() / getEvent():檢視快取內容clear() / delTree() / delEvent():清理快取// Web 模式(自動偵測 $_SERVER['REQUEST_METHOD'] 與 REQUEST_URI)
$router->clear()->get('/', fn() => 'index')->run();
// CLI / 任務模式(手動指定)
$router->run('get', '/admin/task');
$router = Gene\Router::getRouter();
Gene 路由元件以「約定優於配置」與「流暢介面」設計,讓路由定義既具宣告式清晰度,又保留 PHP 動態語言的彈性。鉤子機制實現橫切關注點(認證、日誌、CORS)的解耦,分組功能解決大型應用路由前綴管理痛點,快取層確保生產效能。適合追求輕量、高彈性的現代 PHP 專案。