use FastRoute\RouteCollector; $dispatcher = FastRoute\simpleDispatcher(function(RouteCollector $r) { $r->addRoute('GET', '/page/{id:\d+}', 'getPageHandler'); }); // Match the requested route $routeInfo = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']); if ($routeInfo[0] == FastRoute\Dispatcher::FOUND) { // Get the handler for the matched route $handler = $routeInfo[1]; // Get any route parameters $params = $routeInfo[2]; // Call the appropriate handler function with the parameters call_user_func_array($handler, $params); }
use FastRoute\RouteCollector; $dispatcher = FastRoute\simpleDispatcher(function(RouteCollector $r) { $r->addGroup('/api', function (RouteCollector $r) { $r->addRoute('GET', '/users', 'listUsers'); $r->addRoute('POST', '/users', 'createUser'); $r->addRoute('GET', '/users/{id:\d+}', 'getUser'); $r->addRoute('PUT', '/users/{id:\d+}', 'updateUser'); $r->addRoute('DELETE', '/users/{id:\d+}', 'deleteUser'); }); }); // Match the requested route $routeInfo = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']); if ($routeInfo[0] == FastRoute\Dispatcher::FOUND) { // Get the handler for the matched route $handler = $routeInfo[1]; // Get any route parameters $params = $routeInfo[2]; // Call the appropriate handler function with the parameters call_user_func_array($handler, $params); }In this example, we're defining a group of routes for an API endpoint at /api. We have routes for listing, creating, updating, and deleting users, each of which requires an {id} parameter that must be a digit. The appropriate handler function will be called when any of these routes are requested, with the {id} parameter (if present) passed as an argument. In conclusion, PHP Route pattern is a package library that can be used to define and match routes in a PHP application. The examples provided showcase how easy it is for developers to define and match routes for web pages or API endpoints. The package library used in these examples is FastRoute.