FastRoute Documentation

repository·master·Indexed 26 days ago

https://github.com/nikic/fastroute

A high-performance regular expression-based request router for PHP 8.1+. FastRoute provides flexible routing patterns with support for custom regex constraints, optional segments, and route grouping. It includes features for route caching via cachedDispatcher(), named routes, and a RouteCollector for managing HTTP method registrations (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, ANY).

Tokens
2.3K
Snippets
3
Records
14
Agent score
90%

What's inside FastRoute

  1. Route Pattern Syntax and Placeholders

    master

    FastRoute uses a specific syntax for route patterns:

    • Basic Placeholder: {foo} matches [^/]+.
    • Custom Regex Placeholder: {bar:[0-9]+} allows you to specify a custom regular expression. Note: Custom patterns cannot use capturing groups like (en|de). Use non-capturing groups (?:en|de) instead.
    • Optional Parts: Parts enclosed in [...] are optional. Optional parts must be at the end of the route pattern.

    Examples:

    • /user/{id:\d+} matches /user/42 but not /user/xyz.
    • /user/{name:.+} matches /user/foo/bar.
    • /user/{id:\d+}[/{name}] matches both /user/123 and /user/123/john.
    • /user[/{id:\d+}[/{name}]] supports nested optional parts.
  2. Basic Usage of FastRoute

    master

    To use FastRoute, use FastRoute\simpleDispatcher to define your routes and then call dispatch() on the returned dispatcher. You must manually provide the HTTP method and the URI (after stripping the query string and decoding it).

    <?php
    
    require '/path/to/vendor/autoload.php';
    
    $dispatcher = FastRoute\
    simpleDispatcher(function(FastRoute\\ConfigureRoutes $r) {
        $r->addRoute('GET', '/users', 'get_all_users_handler');
        // {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');
    });
    
    // Fetch method and URI from somewhere
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $uri = $_SERVER['REQUEST_URI'];
    
    // Strip query string (?foo=bar) and decode 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;
    }
  3. Enable Route Caching with cachedDispatcher()

    master

    To improve performance, use FastRoute\cachedDispatcher() instead of simpleDispatcher(). This allows you to cache the generated routing data to a file.

    Options array keys:

    • cacheKey: (Required) The key/location for the cache (e.g., a file path).
    • cacheDisabled: (Optional) Boolean to disable caching. Defaults to true (enabled by default in some contexts, check your environment).
    • cacheDriver: (Optional) The class name or instance of the cache driver. Defaults to FastRoute\Cache\FileCache::class.
  4. Dispatching URIs and Handling Results

    master

    The dispatch($httpMethod, $uri) method returns an array containing the routing result. The first element is the status code:

    • FastRoute\Dispatcher::NOT_FOUND (0): The URI was not found.
    • FastRoute\Dispatcher::METHOD_NOT_ALLOWED (2): The URI exists but does not support the requested HTTP method. The second element of the array contains a list of allowed methods (e.g., ['GET', 'POST']).
    • FastRoute\Dispatcher::FOUND (1): The route matched. The second element is the $handler and the third element is an associative array of placeholder variables.
  5. Define Routes with addRoute()

    master

    Routes are added using the addRoute() method on a FastRoute\ConfigureRoutes instance.

    Signature: $r->addRoute($method, $routePattern, $handler);

    • $method: An uppercase HTTP method string (e.g., 'GET') or an array of strings (e.g., ['GET', 'POST']).
    • $routePattern: The URI pattern.
    • $handler: Any data associated with the route (callback, class name, etc.).

    Shortcut methods: You can also use $r->get(), $r->post(), $r->put(), $r->patch(), $r->delete(), and $r->head().

  6. Override Route Parser, Data Generator, and Dispatcher

    master

    You can customize the routing engine by providing different implementations for the RouteParser, DataGenerator, and Dispatcher interfaces via the options array in simpleDispatcher or cachedDispatcher.

    Note: The DataGenerator and Dispatcher should always be changed as a pair because their data formats are tightly coupled. The RouteParser can be changed independently.

    Available Options:

    • routeParser: Class name for the parser.
    • dataGenerator: Class name for the generator.
    • dispatcher: Class name for the dispatcher.
    $dispatcher = FastRoute\\simpleDispatcher(function(FastRoute\\ConfigureRoutes $r) {
        /* ... */
    }, [
        'routeParser' => 'FastRoute\\RouteParser\\Std',
        'dataGenerator' => 'FastRoute\\DataGenerator\\MarkBased',
        'dispatcher' => 'FastRoute\\Dispatcher\\MarkBased',
    ]);
  7. Register named routes in RouteCollector

    master
    You can assign a name to a route by passing a ROUTE_NAME key within the $extraParameters array in any route definition method. This allows for URI generation (if supported by your implementation). Note that route names must be unique strings; attempting to reuse a name will throw a BadRouteException.
  8. Define routes using RouteCollector

    master
    The RouteCollector class is used to define and collect routes for the application. You can register routes for specific HTTP methods or use convenience methods for common verbs. Routes can also be grouped under a common prefix using addGroup.
  9. Reference BadRouteException factory methods

    master

    The BadRouteException class uses the following static methods to throw specific errors during route definition:

    • alreadyRegistered(string $route, string $method): Thrown when two routes match the same path and HTTP method.
    • namedRouteAlreadyDefined(string $name): Thrown when two routes are assigned the same name.
    • invalidRouteName(mixed $name): Thrown when a route name is not a non-empty string.
    • shadowedByVariableRoute(string $route, string $shadowedRegex, string $method): Thrown when a static route is unreachable because a previously defined variable route matches it.
    • placeholderAlreadyDefined(string $name): Thrown when the same placeholder name is used multiple times in a route.
    • variableWithCaptureGroup(string $regexPart, string $name): Thrown when a custom regex for a parameter contains an illegal capturing group.