VOOZH about

URL: https://deepwiki.com/hypervel/router/2.2-route-collection-and-registration

⇱ Route Collection and Registration | hypervel/router | DeepWiki


Loading...
Menu

Route Collection and Registration

Purpose and Scope

This document explains how routes are collected and registered in the Hypervel Router system. It covers the RouteCollector class, which processes route definitions, handles route groups, manages named routes, and integrates with middleware systems. It also covers RouteFileCollector, which manages the loading of route files.

For information about how routes are initially defined using the Router API, see Router Class. For details on how collected routes are dispatched, see Route Dispatching and Initialization.

RouteCollector Overview

The RouteCollector class src/RouteCollector.php13 extends Hyperf's base RouteCollector to add support for named routes, enhanced options handling, and integration with middleware exclusion management. It serves as the central collection point where route definitions are processed, parsed, and prepared for the routing system.

Core Responsibilities

ResponsibilityDescription
Route ParsingParses route patterns using FastRoute's RouteParser
Named RoutesMaintains a registry of named routes in $namedRoutes
HTTP MethodsProvides convenience methods for common HTTP verbs
Route GroupsHandles nested groups with prefix and namespace inheritance
Middleware IntegrationRegisters middleware and exclusions with MiddlewareManager
Handler WrappingWraps route handlers in RouteHandler objects

Sources: src/RouteCollector.php13-89

Route Registration Architecture


Sources: src/RouteCollector.php53-81

HTTP Method Registration

The RouteCollector provides convenience methods for registering routes with specific HTTP methods. All methods delegate to the core addRoute() method.

Convenience Methods

MethodHTTP MethodsLine Reference
options()OPTIONSsrc/RouteCollector.php26-29
match()Custom array of methodssrc/RouteCollector.php37-40
any()GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONSsrc/RouteCollector.php48-51

The addRoute Method

The addRoute() method src/RouteCollector.php53-81 is the core registration function that performs the following steps:


Sources: src/RouteCollector.php53-81

Named Routes Management

Named routes allow routes to be referenced by name rather than by their URI pattern, enabling stable URL generation even when route patterns change.

Named Route Storage

Named routes are stored in the $namedRoutes array src/RouteCollector.php18 with the route name as the key and the parsed route data as the value. The name is specified via the 'as' option:


Route Existence Checking

The has() method src/RouteCollector.php94-102 checks if one or more named routes exist using array difference operations on flipped arrays.

Sources: src/RouteCollector.php18 src/RouteCollector.php70-72 src/RouteCollector.php86-102

Route Groups and Prefixes

Route groups allow common attributes (prefixes, namespaces, middleware) to be applied to multiple routes. The RouteCollector handles nested groups through option merging and prefix concatenation.

Group Prefix Application


The prefix concatenation is handled by getRouteWithPrefix() src/RouteCollector.php172-182 which:

  1. Trims slashes from both prefix and route
  2. Handles empty prefixes (returns '/' for empty routes)
  3. Concatenates with proper slash formatting

Sources: src/RouteCollector.php164-182

Namespace Handling

When a route handler is a string and a namespace option exists in currentGroupOptions, the namespace is prepended to the handler string src/RouteCollector.php134-136 This allows controller class names to be specified relative to a group namespace.

Sources: src/RouteCollector.php128-139

Options Merging

The mergeOptions() method src/RouteCollector.php104-113 combines group-level and route-level options, with special handling for the 'as' (name) option.

Named Route Concatenation

When both group and route specify an 'as' option, they are concatenated with a dot separator:


This is handled at src/RouteCollector.php106-108

Recursive Merging

After handling the 'as' option specially, array_merge_recursive() combines the remaining options src/RouteCollector.php112 This allows arrays like middleware to be merged across group levels.

Sources: src/RouteCollector.php104-113

Handler Parsing

The parseHandlerAndOptions() method src/RouteCollector.php115-126 handles multiple route definition syntaxes.

Handler Formats

FormatExampleProcessing
String or non-array'UserController@index'Decorated with namespace
Array with options['uses' => 'UserController']Extract options
Tuple format[UserController::class, 'index']Two-element indexed array
Closure[fn() => 'response']Direct closure

The method distinguishes between:

Action Extraction

The parseAction() method src/RouteCollector.php141-157 extracts the actual handler from various formats:

  1. Two-element indexed array (tuple)
  2. Array with 'uses' key
  3. Array with Closure at index 0
  4. Otherwise throws InvalidArgumentException

Sources: src/RouteCollector.php115-162

Middleware Integration

Route middleware is registered with the Hyperf MiddlewareManager during route registration src/RouteCollector.php76 The middleware array is wrapped using Arr::wrap() to ensure it's always an array.

Middleware Exclusions

Middleware exclusions (specified via 'without_middleware' option) are registered separately with MiddlewareExclusionManager src/RouteCollector.php79 These exclusions are applied after middleware group expansion to filter out specific middleware from groups.


Sources: src/RouteCollector.php76 src/RouteCollector.php79

RouteFileCollector

The RouteFileCollector class src/RouteFileCollector.php7 manages the list of PHP files containing route definitions. It is used by DispatcherFactory to load routes during initialization.

Default Configuration

By default, the collector looks for routes at BASE_PATH . '/config/routes.php' src/RouteFileCollector.php14 This can be overridden in the constructor or modified using setter methods.

Route File Management Methods

MethodPurposeLine Reference
__construct(array $routeFiles = [])Initialize with route files or use defaultsrc/RouteFileCollector.php11-15
addRouteFile(string $routeFile)Add a single route filesrc/RouteFileCollector.php17-20
addRouteFiles(array $routeFiles)Add multiple route filessrc/RouteFileCollector.php22-25
setRouteFiles(array $routeFiles)Replace all route filessrc/RouteFileCollector.php27-30
getRouteFiles()Retrieve current route filessrc/RouteFileCollector.php32-35

File Deduplication

The addRouteFiles() method uses array_unique() and array_merge() to prevent duplicate file paths src/RouteFileCollector.php24

Sources: src/RouteFileCollector.php1-37

Route Data Flow


Sources: src/RouteCollector.php53-81

Integration with Hyperf Framework

The RouteCollector extends Hyperf\HttpServer\Router\RouteCollector src/RouteCollector.php13 inheriting base functionality while adding:

  1. Named route tracking via $namedRoutes property
  2. Enhanced option merging for nested groups via mergeOptions()
  3. Middleware exclusion support via MiddlewareExclusionManager
  4. HTTP method aliases like options(), match(), and any()

The parent class provides:

  • $routeParser - FastRoute parser instance
  • $dataGenerator - FastRoute data generator instance
  • $currentGroupOptions - Current group configuration
  • $currentGroupPrefix - Current group prefix
  • $server - Server name for route registration

Sources: src/RouteCollector.php10 src/RouteCollector.php13