nikic/fast-route
FastRoute is a high-performance PHP 8.1+ request router using compiled regular expressions. Define routes with patterns and parameters (optional segments, constraints), dispatch by HTTP method and URI, and get NOT_FOUND, METHOD_NOT_ALLOWED, or FOUND with handler and vars.
Install FastRoute with composer require nikic/fast-route, ensuring you’re on PHP 8.1+. Begin by creating a simpleDispatcher with inline route definitions to quickly prototype routing logic. Start with a minimal HTTP application skeleton: extract $httpMethod and $uri from the request context (e.g., $_SERVER for web SAPI), strip the query string, decode the URI, then call $dispatcher->dispatch(). Use the returned status code (NOT_FOUND, METHOD_NOT_ALLOWED, or FOUND) to route control flow — for FOUND, invoke your handler (e.g., a callable, controller, or closure) with the captured parameters. This gives a fully working router in under 30 lines.
Define all routes inside a closure passed to simpleDispatcher (development) or cachedDispatcher (production). Group related routes using addGroup() for cleaner organization (e.g., /api/v1, /admin). Leverage shorthand methods ($r->get(), $r->post(), etc.) to reduce boilerplate, and use named placeholders with regex constraints (e.g., {id:\d+}) for type-safe parameter extraction. Handlers can be strings (e.g., service names for a DI container), callables, invokables, or controller/action tuples — FastRoute only resolves the mapping. For complex routing, build reusable route collectors (e.g., per module) and merge them in the main dispatcher. Use cachedDispatcher in production to avoid rebuilding routing data on every request — configure cacheKey, and optionally cacheDriver (e.g., FileCache or custom PSR-6/16 implementation).
/posts[{/id}] is invalid). Nested optionals like /user[/{id:\d+}[/{name}]] work but should be used sparingly to preserve readability.( and ) in placeholder patterns — use non-capturing (?:...) or pipe syntax ({lang:en|de}) to prevent regex conflicts.cacheKey (e.g., append app version) on route changes, or set cacheDisabled via environment variable (IS_DEBUG_ENABLED).Allow header from $routeInfo[1] — FastRoute provides it, but does not auto-include it in responses.cachedDispatcher, the cacheDriver can be a class name or instance — useful for injecting a PSR-6 cache pool. If overridden, ensure DataGenerator and Dispatcher implementations match (e.g., MarkBased ↔ MarkBased).How can I help you explore Laravel packages today?