middlewares/fast-route
PSR-15 middleware that integrates FastRoute for route matching and handler discovery. Adds the matched handler and route parameters as request attributes, and can generate 404/405 responses via a PSR-17 response factory (auto-detected by default).
Installation
composer require middlewares/fast-route
Register the middleware in app/Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
// ...
\FastRoute\Middleware\FastRouteMiddleware::class,
],
];
Define Routes
Create a route definition file (e.g., routes/fast-routes.php):
return [
'GET /dashboard' => \App\Http\Controllers\DashboardController::class . '@index',
'POST /api/login' => \App\Http\Controllers\AuthController::class . '@login',
];
Configure Middleware Publish the config (if needed) and define route groups:
FastRouteMiddleware::setRoutes(require base_path('routes/fast-routes.php'));
First Use Case Dispatch a request through the middleware in a controller or directly:
$dispatcher = FastRouteMiddleware::getDispatcher();
$routeInfo = $dispatcher->dispatch('GET', '/dashboard');
Route Dispatching Use the middleware to resolve routes dynamically:
$middleware = new FastRouteMiddleware();
$response = $middleware->process($request, function ($request) {
$dispatcher = FastRouteMiddleware::getDispatcher();
$routeInfo = $dispatcher->dispatch($request->method(), $request->getUri()->getPath());
// Handle route resolution...
});
Route Grouping Group routes by prefix or middleware:
FastRouteMiddleware::addGroup('/admin', [
'GET /users' => \App\Http\Controllers\Admin\UserController::class . '@index',
], ['middleware' => ['auth']]);
Integration with Laravel
FastRouteMiddleware early in the stack to intercept routes before Laravel’s router.$this->app->singleton(\FastRoute\Dispatcher::class, function () {
return FastRouteMiddleware::getDispatcher();
});
Dynamic Route Loading Load routes from multiple files or databases:
$routes = [];
foreach (glob(base_path('routes/*.php')) as $file) {
$routes = array_merge($routes, require $file);
}
FastRouteMiddleware::setRoutes($routes);
Caching Routes Cache the dispatcher for performance:
$dispatcher = FastRouteMiddleware::getCachedDispatcher();
// Or cache manually:
FastRouteMiddleware::cacheDispatcher(base_path('bootstrap/cache/fast-route.php'));
Route Overrides
FastRouteMiddleware is placed before Laravel’s router middleware in Kernel.php.FastRouteMiddleware::setPriority(true) to force precedence.Case Sensitivity
$dispatcher = FastRoute\simpleDispatcher([
strtolower('GET /dashboard') => \App\Http\Controllers\DashboardController::class . '@index',
]);
Route Parameters
: for parameters (e.g., GET /users/{id}). Laravel’s router uses {id}. Ensure consistency or map parameters explicitly:
$routeInfo = $dispatcher->dispatch($request->method(), $request->getUri()->getPath());
$params = $routeInfo[2]; // Extract parameters
Caching Quirks
php artisan cache:clear
FastRouteMiddleware::setCacheEnabled(false);
Middleware Chaining
$middleware = new FastRouteMiddleware();
$response = $middleware->process($request, function ($request) use ($middleware) {
$routeInfo = $dispatcher->dispatch($request->method(), $request->getUri()->getPath());
return app()->handle($request); // Proceed with Laravel middleware
});
Inspect Route Matches Log route info for debugging:
$routeInfo = $dispatcher->dispatch('GET', '/dashboard');
logger()->debug('Route matched:', ['info' => $routeInfo]);
Validate Routes Use FastRoute’s built-in validator:
$validator = new FastRoute\RouteCollector(new FastRoute\RouteParser\Std(), new FastRoute\DataGenerator\GroupCountBased());
$validator->addRoute('GET', '/test', function () {});
$validator->getData();
Performance Profiling Measure dispatcher time:
$start = microtime(true);
$dispatcher->dispatch('GET', '/slow-route');
logger()->info('Dispatch time:', [microtime(true) - $start]);
Custom Route Parsers
Extend FastRoute\RouteParser\Std for custom syntax:
$parser = new class extends FastRoute\RouteParser\Std {
public function parseRoute(string $route): array {
// Custom logic
}
};
FastRouteMiddleware::setRouteParser($parser);
Event Hooks Listen to route dispatch events:
FastRouteMiddleware::onDispatch(function ($routeInfo, $request) {
// Pre-dispatch logic
});
Integration with API Platforms Use FastRoute for high-performance API gateways:
$dispatcher = FastRouteMiddleware::getDispatcher();
$response = $dispatcher->dispatch($request->method(), $request->getUri()->getPath());
if ($response[0] === FastRoute\Dispatcher::NOT_FOUND) {
return response()->json(['error' => 'Not found'], 404);
}
How can I help you explore Laravel packages today?