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.
Introduction
FastRoute is a lightweight, high-performance PHP routing library that uses a dispatcher pattern to match incoming HTTP requests to registered routes. It provides a simple yet powerful API for defining routes and handling different HTTP methods.How FastRoute Works
FastRoute operates on a three-step process:- Route Registration: Define your routes using a RouteCollector
- Dispatcher Creation: Compile routes into an optimized dispatcher
- Route Matching: Match incoming requests and execute handlers
Creating the Dispatcher
The dispatcher is created usingFastRoute\simpleDispatcher(), which accepts a callback function that receives a RouteCollector instance:
index.php
The dispatcher compiles all routes into an optimized data structure for fast lookups. This happens once during initialization.
Dispatching Requests
Once the dispatcher is created, you can match incoming requests by calling thedispatch() method with the HTTP method and URI:
index.php
$routeInfo[0]- Status code (FOUND, NOT_FOUND, or METHOD_NOT_ALLOWED)$routeInfo[1]- Handler function (when route is found)$routeInfo[2]- Array of route parameters (when route is found)
Basic Route Registration
Routes are registered using theRouteCollector instance. Here are examples of basic routes:
Simple GET Routes
web.php
Multiple HTTP Methods
You can register the same route for different HTTP methods:api.php
Route Handlers
Handlers can be either:- String callbacks: Function names that will be called
- Closures: Anonymous functions defined inline
api.php
Organizing Routes
It’s a best practice to organize routes into separate files based on functionality (e.g.,api.php for API routes, web.php for web routes). Each route file returns a function that accepts the RouteCollector:
web.php
Next Steps
Route Dispatcher
Learn how the dispatcher handles different route outcomes
Route Parameters
Add dynamic parameters to your routes