VOOZH about

URL: https://deepwiki.com/hypervel/router/4.5-middleware-configuration-and-exclusions

⇱ Middleware Configuration and Exclusions | hypervel/router | DeepWiki


Loading...
Menu

Middleware Configuration and Exclusions

Purpose and Scope

This document explains how middleware is registered with routes and how specific middleware can be excluded using the without_middleware option. It covers the interaction between RouteCollector, Hyperf's MiddlewareManager, and the MiddlewareExclusionManager class that handles exclusions after middleware group expansion.

For details on specific middleware implementations, see:

For the broader middleware architecture overview, see Middleware System.


Middleware Registration on Routes

Middleware is assigned to routes through the middleware option when defining routes. The RouteCollector class processes these assignments and registers them with Hyperf's MiddlewareManager.

Registration Flow


Sources: src/RouteCollector.php53-81

Code Implementation

The registration happens in the addRoute method:

RouteCollector::addRoute() performs two key operations:

1. Middleware registration (line 76):
 MiddlewareManager::addMiddlewares($this->server, $route, $method, Arr::wrap($options['middleware'] ?? []))

2. Exclusion storage (line 79):
 MiddlewareExclusionManager::addExcluded($this->server, $route, $method, Arr::wrap($options['without_middleware'] ?? []))

The middleware array is wrapped with Arr::wrap() to handle both string and array inputs, then stored without any filtering. Exclusions are stored separately to be applied after middleware groups are expanded by Hyperf's framework.

Sources: src/RouteCollector.php76-79


Middleware Storage Architecture

The system uses two separate storage mechanisms to handle middleware registration and exclusions:


Sources: src/RouteCollector.php76-79 src/MiddlewareExclusionManager.php16-22

Storage Keys

Both storage systems use the same three-level key structure:

LevelDescriptionExample
ServerThe HTTP server name'http'
PathThe route path pattern'/users/{id}'
MethodThe HTTP method (uppercase)'GET', 'POST'

This structure allows efficient lookup during request handling.

Sources: src/MiddlewareExclusionManager.php24-43


Middleware Groups and Expansion

Middleware groups (such as 'web' or 'api') are defined in Hyperf's configuration and expanded by the MiddlewareManager. The without_middleware option works with these groups by applying exclusions after expansion.

Group Expansion Process


This two-phase process ensures that exclusions work correctly even when referencing middleware within named groups.

Sources: src/RouteCollector.php75-79 src/MiddlewareExclusionManager.php1-13


The without_middleware Option

The without_middleware option allows routes to exclude specific middleware from their pipeline, including middleware from groups.

Usage Patterns

The option accepts both string and array values:

Single middleware exclusion:
options['without_middleware'] = 'ThrottleRequests'

Multiple middleware exclusions:
options['without_middleware'] = ['ThrottleRequests', 'ValidateSignature']

MiddlewareExclusionManager Class

The MiddlewareExclusionManager provides a static interface for storing and retrieving exclusions:


Sources: src/MiddlewareExclusionManager.php1-79 src/RouteCollector.php79

Storage Container Structure

The static $container property uses a nested array structure:

MiddlewareExclusionManager::$container structure:

[
 'http' => [ // Server name
 '/users/{id}' => [ // Route path
 'GET' => [ // HTTP method
 'ThrottleRequests', // Excluded middleware
 'ValidateSignature'
 ],
 'POST' => [
 'ValidateSignature'
 ]
 ]
 ]
]

Sources: src/MiddlewareExclusionManager.php16-22


Retrieval and HEAD Request Fallback

The get method retrieves exclusions for a specific route and includes special handling for HEAD requests:


HEAD Request Logic

When no exclusions are found for a HEAD request, the manager attempts to use exclusions from the corresponding GET route. This maintains consistency with Hyperf's MiddlewareManager behavior.

HEAD request fallback implementation (lines 61-64):

if ($method === 'HEAD') {
 return static::$container[$server][$path]['GET'] ?? [];
}

Sources: src/MiddlewareExclusionManager.php45-68


Middleware Exclusion Validation

The system validates exclusion specifications to prevent common mistakes.

Parameter Restrictions

Middleware exclusions must not include parameters. The InvalidMiddlewareExclusionException enforces this rule:


Exception Message Format

The exception provides a clear error message showing the correct format:

Exception message format (lines 18-20):

"Middleware exclusion '{$middleware}' should not contain parameters. Use '{$name}' instead."

Example:
"Middleware exclusion 'ThrottleRequests:api' should not contain parameters. Use 'ThrottleRequests' instead."

This validation ensures that exclusions target middleware classes rather than specific configurations.

Sources: src/Exceptions/InvalidMiddlewareExclusionException.php1-22


Route Group Option Merging

When routes are defined within groups, middleware options are merged using mergeOptions:


The array_merge_recursive function combines middleware arrays from both group and route definitions, allowing routes to add additional middleware or exclusions to inherited settings.

Sources: src/RouteCollector.php104-113 src/RouteCollector.php62


Testing and Cleanup

The MiddlewareExclusionManager provides a clear method for testing purposes:

Testing support (lines 71-78):

/**
 * Clear all stored exclusions.
 *
 * Useful for testing.
 */
public static function clear(): void
{
 static::$container = [];
}

This method resets the static container, allowing test isolation between test cases.

Sources: src/MiddlewareExclusionManager.php70-78


Integration Summary

The middleware configuration system integrates three key components:

ComponentResponsibilityStorage Location
RouteCollectorParses route options and delegates storageN/A (delegates to others)
MiddlewareManagerStores middleware assignments, expands groupsMiddlewareManager::$container (Hyperf)
MiddlewareExclusionManagerStores exclusions, applies after expansionMiddlewareExclusionManager::$container (static)

This separation allows the exclusion system to work correctly with middleware groups by deferring filtering until after group expansion.

Sources: src/RouteCollector.php76-79 src/MiddlewareExclusionManager.php14-22