nikic/fast-route
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
nikic/fast-route is an open-source PHP library that provides a fast implementation of a regular expression-based router. It helps in routing HTTP requests to specific handle callbacks based on the request methods and URI patterns. The router allows you to define sophisticated routing patterns with placeholder and optional segments, handle common request methods, and also supports route grouping for better organization and controlled routing. Additionally, nikic/fast-route offers features such as route data caching for enhanced performance and also supports overwriting the route parser and dispatcher for greater customization.
To use nikic/fast-route, start by installing the package with Composer by running the command composer require nikic/fast-route
. After installation, you can load the library through Composer's autoloader and use it in your PHP application. A simple example of using nikic/fast-route would look like this:
<?php
require '/path/to/vendor/autoload.php';
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/users', 'get_all_users_handler');
$r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler');
$r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_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:
// ... 404 Not Found
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// ... 405 Method Not Allowed
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// ... call $handler with $vars
break;
}
The routes are defined within the simpleDispatcher()
function, and you can specify different HTTP methods, URIs, and handlers for the different routes. The library will then match the current HTTP request method and URI to the defined routes and call the appropriate handler.
The nikic/fast-route documentation is included in the README file on the project's GitHub repository, available at https://github.com/nikic/FastRoute. The documentation provides an informative guide on the usage of the library with various examples on defining routes, handling different HTTP methods, using route groups and caching, and also overwriting custom route parsers and dispatchers.