<?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; }