Documentation Index
Fetch the complete documentation index at: https://mintlify.com/MonishAMPT/fastroute-code/llms.txt
Use this file to discover all available pages before exploring further.
The Dispatcher’s Role
The FastRoute dispatcher is responsible for matching incoming HTTP requests against registered routes and determining the appropriate action. It returns one of three possible outcomes that you must handle in your application.Dispatcher Result Types
When you call$dispatcher->dispatch($method, $uri), FastRoute returns an array where the first element indicates the match result:
1. FOUND
The route was successfully matched. The array contains:[0]-FastRoute\Dispatcher::FOUND[1]- The route handler[2]- Array of route parameters (if any)
2. NOT_FOUND
No route matches the requested URI.3. METHOD_NOT_ALLOWED
A route matches the URI, but not for the requested HTTP method (e.g., POST was used when only GET is allowed).Handling Dispatcher Results
You must implement logic to handle all three possible outcomes. Here’s the complete implementation:index.php
Detailed Breakdown
Handling NOT_FOUND (404)
When no route matches, return a 404 response:index.php
Handling METHOD_NOT_ALLOWED (405)
When the route exists but the HTTP method is wrong:index.php
/api/test, the dispatcher will return METHOD_NOT_ALLOWED.
Handling FOUND (200)
When a route is successfully matched, execute the handler:index.php
call_user_func(), passing any route parameters as an argument.
$routeInfo[2] contains an array of matched route parameters. Even if your route has no parameters, you should still pass it to the handler for consistency.Setting Content Type Headers
Before handling the dispatcher result, you can set appropriate content type headers based on the route:index.php
Complete Request Flow
- Extract HTTP method and URI from
$_SERVER - Parse and clean the URI
- Create the dispatcher with registered routes
- Dispatch the request
- Set content type headers
- Handle the result using a switch statement
- Return appropriate response
Best Practices
Always handle all three cases
Always handle all three cases
Never assume a route will be found. Always implement handlers for NOT_FOUND and METHOD_NOT_ALLOWED to provide meaningful error messages.
Set HTTP status codes correctly
Set HTTP status codes correctly
Use
header() to set the appropriate HTTP status code (404, 405, 200) before sending response content.Pass parameters to handlers
Pass parameters to handlers
Always pass
$routeInfo[2] to your handlers, even if empty, to maintain a consistent function signature.Next Steps
Route Parameters
Learn how to work with dynamic route parameters
Route Groups
Organize routes with common prefixes