VOOZH about

URL: https://deepwiki.com/hypervel/components/3.2-routing-and-dispatching

⇱ Routing and Dispatching | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

Routing and Dispatching

Purpose and Scope

This document explains the routing system in Hypervel, covering route registration, dispatching, named routes, route groups, model binding, and the lazy initialization mechanism. The routing layer is responsible for mapping HTTP requests to controller handlers and managing route-level middleware.

For URL generation from routes, see URL Generation and Signed URLs. For middleware execution details, see Middleware Pipeline. For the complete request lifecycle, see Request Lifecycle and Processing.


Architecture Overview

The Hypervel routing system extends Hyperf's routing infrastructure with Laravel-compatible features while maintaining coroutine safety. The system uses lazy initialization to defer route loading until the first request, and stores named routes for URL generation.


Sources: src/router/src/DispatcherFactory.php1-51 src/router/src/Router.php1-189 src/router/src/RouteCollector.php1-183


DispatcherFactory and Lazy Initialization

The DispatcherFactory class manages route initialization and provides RouteCollector instances for different servers. It implements a lazy initialization pattern where routes are not loaded until the first request.

Initialization Sequence


The initialized flag ensures routes are loaded exactly once, even in a coroutine environment with multiple concurrent requests.

Key behaviors:

AspectImplementation
Initialization timingDeferred until getRouter() first called
Flag tracking$initialized property prevents re-initialization
Route file discoveryFetches from RouteFileCollector at init time
Service provider routesRoutes added via loadRoutesFrom() are included

Sources: src/router/src/DispatcherFactory.php15-50 tests/Router/DispatcherFactoryTest.php86-121


RouteCollector: Route Registration

The RouteCollector class extends Hyperf's base RouteCollector with additional HTTP methods, named route support, and enhanced option handling.

Route Registration Methods


Handler and Options Parsing

The RouteCollector supports multiple handler formats:

Handler FormatExampleDescription
String'UserController::index'Controller class and method
Array (positional)['UserController', 'index']Class and method as array
Closurefunction() { ... }Anonymous function
Options array['uses' => 'UserController::index', 'as' => 'users']Handler in options

Sources: src/router/src/RouteCollector.php53-81 src/router/src/RouteCollector.php115-162


Named Routes

Named routes provide a stable identifier for URL generation, independent of the route's URI pattern. The RouteCollector stores named routes in a namedRoutes array mapping names to route data.

Named Route Storage


Hierarchical Named Routes with Groups

When routes are defined within groups, the group's as option is prepended to the route's name with a dot separator:


The concatenation logic is in mergeOptions():

if (isset($origin['as'])) {
 $options['as'] = $origin['as'] . (isset($options['as']) ? '.' . $options['as'] : '');
}

Methods:

MethodPurpose
getNamedRoutes()Returns all named routes as array
has(string|array $name)Checks if named route(s) exist

Sources: src/router/src/RouteCollector.php70-71 src/router/src/RouteCollector.php86-102 src/router/src/RouteCollector.php104-113 tests/Router/RouteCollectorTest.php200-243


Route Groups

Route groups allow multiple routes to share common attributes like prefixes, middleware, and namespaces.

Group Options

OptionTypeDescriptionExample
prefixstringURI prefix for all routes'/api'
middlewarearrayMiddleware for all routes['auth', 'throttle']
without_middlewarearrayMiddleware to exclude['csrf']
namespacestringController namespace prefix'App\\Http\\Controllers\\Admin'
asstringNamed route prefix'admin.'

Group Processing Flow


Namespace Processing

When a namespace option is provided, it's prepended to string handlers:

namespace: 'App\\Http\\Controllers\\Admin'
handler: 'UserController::index'
result: 'App\\Http\\Controllers\\Admin\\UserController::index'

This occurs in getDecoratedHandler() which is called during handler parsing.

Sources: src/router/src/RouteCollector.php53-81 src/router/src/RouteCollector.php104-113 src/router/src/RouteCollector.php128-139 src/router/src/RouteCollector.php164-182 tests/Router/RouteCollectorTest.php74-108 tests/Router/RouteCollectorTest.php245-262


Router Facade and API

The Router class provides a high-level API for route registration and acts as a facade to the DispatcherFactory. It also manages model bindings for route parameters.

Router Delegation Pattern


The Router implements the delegation pattern via __call():


This allows the Router to proxy all RouteCollector methods while adding its own functionality.

Sources: src/router/src/Router.php49-54 src/router/src/Router.php183-188


Model Binding

The Router supports automatic model resolution for route parameters. When a route parameter matches a registered binding, the framework automatically fetches the model instance.

Binding Types


Model Binding Methods

MethodParametersPurpose
model()$param, $modelClassRegister model class for parameter
bind()$param, Closure $callbackRegister custom resolver closure
getModelBinding()$paramRetrieve model class for parameter
getExplicitBinding()$paramRetrieve closure for parameter

Validation: The model() method validates that the class exists and extends Hyperf\Database\Model\Model.

Sources: src/router/src/Router.php26-36 src/router/src/Router.php104-139


Route File Loading

Route files are managed through the RouteFileCollector which maintains an array of file paths to load during route initialization.

Route File Collection Flow


RouteFileCollector API

MethodPurpose
__construct(array $routeFiles)Initialize with default route files
addRouteFile(string $file)Add single route file
addRouteFiles(array $files)Add multiple route files
setRouteFiles(array $files)Replace all route files
getRouteFiles()Retrieve current route file list

Default behavior: If no route files are provided, defaults to BASE_PATH . '/config/routes.php'.

Uniqueness: The addRouteFiles() method uses array_unique() to prevent duplicate file loading.

Sources: src/router/src/RouteFileCollector.php1-36 src/router/src/DispatcherFactory.php22-36 tests/Router/DispatcherFactoryTest.php86-121


Service Provider Integration

The RouteServiceProvider base class provides a convenient pattern for registering route files from service providers.

RouteServiceProvider Pattern


Implementation:


This pattern allows packages to register their route files during the service provider boot phase, ensuring they're available when the DispatcherFactory initializes routes.

Sources: src/foundation/src/Support/Providers/RouteServiceProvider.php1-23


Current Route Resolution

The Router provides methods to access the currently dispatched route instance during request processing.

Current Route Methods

MethodReturn TypeDescription
current()?DispatchedRouteGet current route instance
getCurrentRoute()?DispatchedRouteAlias for current()
currentRouteName()?stringGet current route name
input()mixedGet route parameter value

Route Resolution Flow


The current route is retrieved from the Request object, which stores it in the coroutine-safe Context during request dispatching.

Sources: src/router/src/Router.php144-181


Group Registration with Files

The Router::group() method supports both callbacks and file paths for defining grouped routes:


File validation: The registerRouteFile() method checks file existence and throws RuntimeException if the file doesn't exist.

Sources: src/router/src/Router.php59-68 src/router/src/Router.php83-90


Configuration and Dependency Injection

The router system integrates with Hyperf's dependency injection through the ConfigProvider.

Dependency Bindings

Interface/Base ClassImplementation
Hyperf\HttpServer\Router\DispatcherFactoryHypervel\Router\DispatcherFactory
FastRoute\RouteParserFastRoute\RouteParser\Std
FastRoute\DataGeneratorFastRoute\DataGenerator\GroupCountBased
Hyperf\HttpServer\Router\RouteCollectorHypervel\Router\RouteCollector
UrlGeneratorContractHypervel\Router\UrlGenerator

These bindings ensure Hypervel's enhanced routing classes are used instead of Hyperf's base implementations.

Sources: src/router/src/ConfigProvider.php1-29


Server-Specific Routes

The router supports defining routes for different servers (e.g., HTTP, WebSocket) through the addServer() method:


During the callback execution, all routes are registered to the specified server. The server name is automatically reset to 'http' after the callback completes.

Sources: src/router/src/Router.php42-47