<?php require 'vendor/autoload.php'; // 通过 FastRoutesimpleDispatcher() 方法定义路由,第一个参数必须是 FastRouteRouteCollector实例 $dispatcher = FastRoutesimpleDispatcher(function (FastRouteRouteCollector $r) { /** * 通过 addRoute() 添加路由 * $method 必须是大写,可以写成数组形式 * $routePattern /开头, 可以用正则修饰 * $handler */ $r->addRoute('GET', '/fast-route/demo1.php/{name:w+}', 'say_handler'); // 分组 $r->addGroup('/admin', function (FastRouteRouteCollector $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 = FastRoutecachedDispatcher(function(FastRouteRouteCollector $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 FastRouteDispatcher::NOT_FOUND: echo '... 404 Not Found'; break; case FastRouteDispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; echo '... 405 Method Not Allowed'; break; case FastRouteDispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; var_dump('... call', $handler, 'with', $vars); break; }