davenusbaum / jaunt
基于树的路由器
v0.0.1
2024-05-20 14:11 UTC
Requires
- php: >=7.1.0
Requires (Dev)
- phpunit/phpunit: >=7.0 < 10
README
Jaunt,一个快速的基于树的PHP路由器。
PHP路由器的一个最大挑战是它们会为每个请求重新开始。Jaunt的设计是为了通过构建和遍历基于树的架构来简化并加速查找路由的过程,而不是迭代基于正则表达式的路由定义列表。
Jaunt使用由Kaloyan Tsvetkov创建的优秀的benchmark-php-routing包进行了基准测试。
创建一个路由器
创建路由器很简单。
<?php
use Jaunt\Router;
$router = new Router();
添加路由
通过使用相应类方法添加HTTP方法、提供路径和路由目标来添加路由。路由目标的意义是开放的,路由器的目标是找到并返回目标。动态路由可以包括包裹在{}
中的占位符。
$router = (new Router())
->get('/api/account', 'get_all_accounts_handler');
->get('/api/account/:id', 'get_account_handler');
->get('/api/account/:id/users', 'get_account_users_handler');
添加中间件
可以在路由的任何位置添加中间件。
$router = (new Router())
->use('/api/', 'auth_middleware')
->use('/api/account', 'account_access_middleware')
->get('/api/account', 'get_all_accounts_handler');
->get('/api/account/:id', 'get_account_handler');
->get('/api/account/:id/users', 'get_account_users_handler');
查找路由
route
方法返回一个包含路由信息的数组,包括命名参数的数组和可以作为要调用的处理程序堆栈使用的路由目标数组。
$route = $router->route($method, $path);
缓存路由
可以预先创建并缓存路由以加快创建路由器的过程。
// define the routes
$router = (new Router())
->use('/api/', 'auth_middleware')
->use('/api/account', 'account_access_middleware')
->get('/api/account', 'get_all_accounts_handler');
->get('/api/account/:id', 'get_account_handler');
->get('/api/account/:id/users', 'get_account_users_handler');
// get the resulting route tree
$routeTree = $router->getRouteTree();
// cache the route tree in a php file
file_put_contents('../cache/cached_routes.php','<?php return ' . var_export($route_tree, true) . ';'
在创建路由器时使用缓存的路由树
$router = new Router(include '../cache/cached_routes.php');
$route = $router->route($method, $path);
基本用法示例
<?php
use Jaunt\Router;
require '/path/to/vendor/autoload.php';
$router = (new Router())
->use('/api/', 'auth_middleware')
->use('/api/account', 'account_access_middleware')
->get('/api/account', 'get_all_accounts_handler');
->get('/api/account/:id', 'get_account_handler');
->get('/api/account/:id/users', 'get_account_users_handler');
// Fetch method and URI from somewhere
$method = $_SERVER['REQUEST_METHOD'];
$path = url_parse($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$route = $router->route($method, $path);