fast-route的使用
<?php require 'vendor/autoload.php'; // 通过 FastRoute\simpleDispatcher() 方法定义路由,第一个参数必须是 FastRoute\RouteCollector实例 $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { /** * 通过 addRoute() 添加路由 * $method 必须是大写,可以写成数组形式 * $routePattern /开头, 可以用正则修饰 * $handler */ $r->addRoute('GET', '/fast-route/demo1.php/{name:\w+}', 'say_handler'); // 分组 $r->addGroup('/admin', function (FastRoute\RouteCollector $r) { // {id} must be a number (\d+) $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); // The /{title} suffix is optional $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler'); $r->addRoute('GET', '/users', 'get_all_users_handler'); }); }); // 使用缓存 $dispatcher2 = FastRoute\cachedDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); $r->addRoute('GET', '/user/{name}', 'handler2'); }, [ 'cacheFile' => __DIR__ . '/route.cache', /* required */ ]); // 获取请求和URI $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI']; // 去除查询字符串(?foo=bar)和解码URI if (false !== $pos = strpos($uri, '?')) { $uri = substr($uri, 0, $pos); } $uri = rawurldecode($uri); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: echo '... 404 Not Found'; break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; echo '... 405 Method Not Allowed'; break; case FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; var_dump('... call', $handler, 'with', $vars); break; }
分情破爱始乱弃,流落天涯思别离。
如花似玉负情意,影如白昼暗自迷。
随风浮沉千叶落,行色匆匆鬓已稀。