PHP开源:route - 高性能的 PHP 路由实现
BrockMuncy
8年前
<h2>Route - 一个快速的 PHP 路由实现</h2> <p> </p> <p>思路参考 <a href="/misc/goto?guid=4959554790305431770" rel="nofollow,noindex">nikic/FastRoute</a> ,实现原理: <a href="/misc/goto?guid=4959741214929194845" rel="nofollow,noindex">Fast request routing using regular expressions</a> 。</p> <h2>示例代码</h2> <pre> <code class="language-php"><?php use Zqhong\Route\Helpers\Arr; use Zqhong\Route\RouteCollector; use Zqhong\Route\RouteDispatcher; require "vendor/autoload.php"; function getUser($uid) { echo "Your uid: " . $uid; } /** @var RouteDispatcher $routeDispatcher */ $routeDispatcher = dispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/user/{id:\d+}', 'getUser'); }); $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = Arr::getValue($_GET, 'r'); $routeInfo = $routeDispatcher->dispatch($httpMethod, $uri); if (Arr::getValue($routeInfo, 'isFound')) { $handler = Arr::getValue($routeInfo, 'handler'); $params = Arr::getValue($routeInfo, 'params'); call_user_func_array($handler, $params); } else { exit('404 NOT FOUND'); }</code></pre> <p>发送请求:</p> <pre> <code class="language-php">// 返回 404 NOT FOUND $ curl http://example.com/?r=ops // 返回:Your uid: 1 $ curl http://example.com/?=/user/1</code></pre> <h2>性能测试</h2> <h2>系统环境</h2> <ul> <li>操作系统:Ubuntu 16.04 LTS(Vultr 4核8G)</li> <li>PHP:7.0.4</li> <li>Apache:2.4.18</li> </ul> <h2>测试结果</h2> <p style="text-align:center"><img src="https://simg.open-open.com/show/132a1fc73484d849d4b1d601dfd28c24.jpg"></p> <pre> <code class="language-php">nikic_route(v1.2) Requests per second: 3527.98 [#/sec] (mean) symfony route(v3.2) Requests per second: 5193.17 [#/sec] (mean) zqhong route(dev-master) Requests per second: 5923.56 [#/sec] (mean)</code></pre> <p>具体的测试代码和结果请看 benchmark 目录。</p> <p> </p> <p> </p> <p> </p>