Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fast Route Laravel Package

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).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require middlewares/fast-route
    

    Register the middleware in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // ...
            \FastRoute\Middleware\FastRouteMiddleware::class,
        ],
    ];
    
  2. 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',
    ];
    
  3. Configure Middleware Publish the config (if needed) and define route groups:

    FastRouteMiddleware::setRoutes(require base_path('routes/fast-routes.php'));
    
  4. First Use Case Dispatch a request through the middleware in a controller or directly:

    $dispatcher = FastRouteMiddleware::getDispatcher();
    $routeInfo = $dispatcher->dispatch('GET', '/dashboard');
    

Implementation Patterns

Core Workflows

  1. 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...
    });
    
  2. Route Grouping Group routes by prefix or middleware:

    FastRouteMiddleware::addGroup('/admin', [
        'GET /users' => \App\Http\Controllers\Admin\UserController::class . '@index',
    ], ['middleware' => ['auth']]);
    
  3. Integration with Laravel

    • Middleware Stack: Place FastRouteMiddleware early in the stack to intercept routes before Laravel’s router.
    • Service Providers: Bind the dispatcher to the container:
      $this->app->singleton(\FastRoute\Dispatcher::class, function () {
          return FastRouteMiddleware::getDispatcher();
      });
      
  4. 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);
    
  5. Caching Routes Cache the dispatcher for performance:

    $dispatcher = FastRouteMiddleware::getCachedDispatcher();
    // Or cache manually:
    FastRouteMiddleware::cacheDispatcher(base_path('bootstrap/cache/fast-route.php'));
    

Gotchas and Tips

Pitfalls

  1. Route Overrides

    • Laravel’s router takes precedence if both are configured. Ensure FastRouteMiddleware is placed before Laravel’s router middleware in Kernel.php.
    • Conflict resolution: Use FastRouteMiddleware::setPriority(true) to force precedence.
  2. Case Sensitivity

    • FastRoute is case-sensitive by default. Normalize paths if case-insensitive routes are needed:
      $dispatcher = FastRoute\simpleDispatcher([
          strtolower('GET /dashboard') => \App\Http\Controllers\DashboardController::class . '@index',
      ]);
      
  3. Route Parameters

    • FastRoute uses : 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
      
  4. Caching Quirks

    • Clear cached routes after changes:
      php artisan cache:clear
      
    • Avoid caching in development. Use:
      FastRouteMiddleware::setCacheEnabled(false);
      
  5. Middleware Chaining

    • FastRouteMiddleware does not automatically apply Laravel middleware. Chain manually:
      $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
      });
      

Debugging Tips

  1. Inspect Route Matches Log route info for debugging:

    $routeInfo = $dispatcher->dispatch('GET', '/dashboard');
    logger()->debug('Route matched:', ['info' => $routeInfo]);
    
  2. 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();
    
  3. Performance Profiling Measure dispatcher time:

    $start = microtime(true);
    $dispatcher->dispatch('GET', '/slow-route');
    logger()->info('Dispatch time:', [microtime(true) - $start]);
    

Extension Points

  1. 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);
    
  2. Event Hooks Listen to route dispatch events:

    FastRouteMiddleware::onDispatch(function ($routeInfo, $request) {
        // Pre-dispatch logic
    });
    
  3. 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);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky