baryshev /tree-route
性能优化的请求路由器
v2.0.0
2015-11-04 23:12 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- codeception/codeception: ^2.1
- codeception/specify: ^0.4.1
This package is not auto-updated.
Last update: 2024-09-18 07:26:53 UTC
README
TreeRoute 是一个专注于性能的请求路由器,支持正则表达式。
安装
使用以下命令安装最新版本: composer require baryshev/tree-route
用法
基本用法
<?php require __DIR__ . '/vendor/autoload.php'; $router = new \TreeRoute\Router(); // Defining route for several HTTP methods $router->addRoute(['GET', 'POST'], '/', 'handler0'); // Defining route for one HTTP method $router->addRoute('GET', '/news', 'handler1'); // Defining route with regular expression param $router->get('/news/{id:[0-9]+}', 'handler2'); // Defining another route with regular expression param $router->get('/news/{slug:[a-zA-Z\-]+}', 'handler3'); // Defining static route that conflicts with previous route, but static routes have high priority $router->get('/news/all', 'handler4'); // Defining another route $router->post('/news', 'handler5'); $method = 'GET'; // Optionally pass HEAD requests to GET handlers // if ($method == 'HEAD') { // $method = 'GET'; // } $url = '/news/1'; $result = $router->dispatch($method, $url); if (!isset($result['error'])) { $handler = $result['handler']; $params = $result['params']; // Do something with handler and params } else { switch ($result['error']['code']) { case 404 : // Not found handler here break; case 405 : // Method not allowed handler here $allowedMethods = $result['allowed']; if ($method == 'OPTIONS') { // OPTIONS method handler here } break; } }
保存和恢复路由(对路由缓存很有用)
<?php require __DIR__ . '/vendor/autoload.php'; $router = new \TreeRoute\Router(); $router->addRoute(['GET', 'POST'], '/', 'handler0'); $router->addRoute('GET', '/news', 'handler1'); $routes = $router->getRoutes(); $anotherRouter = new \TreeRoute\Router(); $anotherRouter->setRoutes($routes); $method = 'GET'; $url = '/news'; $result = $anotherRouter->dispatch($method, $url);
测试
composer install ./vendor/bin/codecept run