VOOZH about

URL: https://deepwiki.com/hypervel/foundation/4.2-middleware-system

⇱ Middleware System | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Middleware System

The middleware system provides HTTP request filtering and processing capabilities in Hypervel Foundation. The system manages middleware registration, resolution, priority ordering, and execution for all incoming HTTP requests through the HasMiddleware trait, which is used by the Kernel class to integrate middleware execution into the request lifecycle.

The middleware system supports multiple middleware types (global, route, groups, aliases), priority-based ordering, middleware exclusion, and aggressive caching of resolved middleware chains. Middleware execution occurs during the HTTP request lifecycle after route dispatching but before controller execution.

For information about the HTTP request lifecycle and how middleware fits into it, see page 4.1. For exception handling during middleware execution, see page 4.4. For automatic form request validation that occurs during dependency resolution (which interacts with middleware), see page 4.3.

Architecture Overview

The middleware system is implemented through the HasMiddleware trait, which is used by the Kernel class. The system supports multiple middleware types, priority-based ordering, parameter passing, and middleware exclusion.

Middleware System Architecture


Sources: src/Http/Kernel.php28-30 src/Http/Traits/HasMiddleware.php15-62 src/Http/Contracts/MiddlewareContract.php11-120

Middleware Types

The system supports four distinct types of middleware organization, each serving different use cases.

TypePropertyPurposeExample
Global$middlewareRuns on every requestCORS, session handling
RouteVia MiddlewareManagerApplied to specific routesAuthentication guards
Groups$middlewareGroupsNamed collections of middlewareweb, api groups
Aliases$middlewareAliasesShortcut names for middleware classesauthAuthMiddleware::class

Middleware Type Resolution


Sources: src/Http/Traits/HasMiddleware.php17-49

Global Middleware

Global middleware is stored in the $middleware array and executes on every HTTP request. This middleware is defined in the HTTP Kernel and forms the base middleware stack.


Methods for managing global middleware:

Sources: src/Http/Traits/HasMiddleware.php17-24 src/Http/Traits/HasMiddleware.php260-291 src/Http/Traits/HasMiddleware.php428-443

Middleware Groups

Middleware groups are named collections of middleware stored in $middlewareGroups. They allow logical grouping of related middleware that can be applied together.


Methods for managing middleware groups:

Sources: src/Http/Traits/HasMiddleware.php26-31 src/Http/Traits/HasMiddleware.php298-331 src/Http/Traits/HasMiddleware.php448-479

Middleware Aliases

Middleware aliases provide convenient shortcuts for middleware class names. They are stored in $middlewareAliases and resolved during middleware resolution.


Methods for managing middleware aliases:

Sources: src/Http/Traits/HasMiddleware.php33-40 src/Http/Traits/HasMiddleware.php484-499

Middleware Resolution and Execution

The middleware resolution process transforms middleware definitions into executable middleware instances, expanding groups and aliases, and applying exclusions.

Middleware Resolution Flow


Sources: src/Http/Traits/HasMiddleware.php66-98 src/Http/Kernel.php78-82

Resolution Process Details

The getMiddlewareForRequest() method src/Http/Traits/HasMiddleware.php66-98 performs the following steps:

  1. Cache Key Generation: Creates a cache key based on server name, route, and HTTP method src/Http/Traits/HasMiddleware.php71-73
  2. Cache Lookup: Returns cached middleware if available src/Http/Traits/HasMiddleware.php75-77
  3. Middleware Collection: Retrieves route-specific middleware from MiddlewareManager src/Http/Traits/HasMiddleware.php80-82
  4. Exclusion Collection: Retrieves excluded middleware from MiddlewareExclusionManager src/Http/Traits/HasMiddleware.php84-86
  5. Middleware Resolution: Calls resolveMiddleware() to expand and filter src/Http/Traits/HasMiddleware.php88-91
  6. Priority Sorting: Applies priority ordering if configured src/Http/Traits/HasMiddleware.php93-95
  7. Cache Storage: Stores result for future requests src/Http/Traits/HasMiddleware.php97

Sources: src/Http/Traits/HasMiddleware.php66-98

Middleware Parsing

The parseMiddleware() method src/Http/Traits/HasMiddleware.php243-255 parses middleware strings with optional parameters:

  • Format: MiddlewareClass:param1,param2,param3
  • Caching: Parsed middleware is cached in $parsedMiddleware src/Http/Traits/HasMiddleware.php52-56
  • Result: Returns ParsedMiddleware object with name, parameters, and signature

Example middleware strings:


Sources: src/Http/Traits/HasMiddleware.php243-255

Resolve Middleware Implementation

The resolveMiddleware() method src/Http/Traits/HasMiddleware.php107-147 expands and filters middleware:

Resolution Logic


Sources: src/Http/Traits/HasMiddleware.php107-147

Key implementation details:

Sources: src/Http/Traits/HasMiddleware.php107-147

Middleware Priority System

The priority system ensures middleware executes in a specific order regardless of registration order. The $middlewarePriority array defines the execution sequence.

Priority Sorting Algorithm


Sources: src/Http/Traits/HasMiddleware.php192-216

Priority Management Methods

The system provides multiple methods for managing middleware priority:

MethodPurposeReference
prependToMiddlewarePriority()Add to beginning of priority listsrc/Http/Traits/HasMiddleware.php336-345
appendToMiddlewarePriority()Add to end of priority listsrc/Http/Traits/HasMiddleware.php350-359
addToMiddlewarePriorityBefore()Insert before specific middlewaresrc/Http/Traits/HasMiddleware.php366-369
addToMiddlewarePriorityAfter()Insert after specific middlewaresrc/Http/Traits/HasMiddleware.php376-379
setMiddlewarePriority()Replace entire priority listsrc/Http/Traits/HasMiddleware.php504-511
getMiddlewarePriority()Retrieve current priority listsrc/Http/Traits/HasMiddleware.php420-423

Relative priority insertion src/Http/Traits/HasMiddleware.php386-415:

  • Accepts single middleware name or array of reference middleware
  • Finds best insertion point based on existing priorities
  • Handles edge cases (beginning, end, not found)

Sources: src/Http/Traits/HasMiddleware.php336-423 src/Http/Traits/HasMiddleware.php504-511

Priority Sorting Implementation

The sorting algorithm src/Http/Traits/HasMiddleware.php192-216 uses a bubble-sort style approach:

  1. Iterates through middleware array
  2. For each middleware in $middlewarePriority, checks if it's out of order
  3. If found out of order, moves it to correct position via moveMiddleware() src/Http/Traits/HasMiddleware.php235-241
  4. Recursively calls itself with the adjusted array
  5. Continues until no moves are needed

Sources: src/Http/Traits/HasMiddleware.php192-241

Middleware Exclusion

Routes can exclude specific middleware using the MiddlewareExclusionManager. The exclusion system operates on fully-resolved middleware class names.

Exclusion Resolution Process


Sources: src/Http/Traits/HasMiddleware.php156-190

Exclusion Rules

  1. No Parameters Allowed: Exclusions cannot contain parameters (e.g., cannot exclude 'throttle:60,1') src/Http/Traits/HasMiddleware.php162-164
  2. Alias Expansion: Excluded aliases are expanded to their class names src/Http/Traits/HasMiddleware.php167-170
  3. Group Expansion: Excluded groups expand to all member middleware src/Http/Traits/HasMiddleware.php173-182
  4. Applied After Resolution: Exclusions are applied after groups/aliases are expanded in the middleware to execute src/Http/Traits/HasMiddleware.php138-144

The InvalidMiddlewareExclusionException is thrown when a parameter-bearing middleware string is used in exclusions src/Http/Traits/HasMiddleware.php163

Sources: src/Http/Traits/HasMiddleware.php156-190

Caching Mechanism

The middleware system implements aggressive caching to avoid repeated resolution on every request.

Cache Key Structure


Sources: src/Http/Traits/HasMiddleware.php66-98

Cache invalidation occurs when:

All cache-invalidating methods set $this->cachedMiddleware = [] to force re-resolution on the next request.

Sources: src/Http/Traits/HasMiddleware.php58-61 src/Http/Traits/HasMiddleware.php274 src/Http/Traits/HasMiddleware.php288 src/Http/Traits/HasMiddleware.php308 src/Http/Traits/HasMiddleware.php328 src/Http/Traits/HasMiddleware.php342 src/Http/Traits/HasMiddleware.php356 src/Http/Traits/HasMiddleware.php412 src/Http/Traits/HasMiddleware.php440 src/Http/Traits/HasMiddleware.php460 src/Http/Traits/HasMiddleware.php476 src/Http/Traits/HasMiddleware.php496 src/Http/Traits/HasMiddleware.php508

Integration with HTTP Kernel

The HTTP Kernel integrates the middleware system into the request lifecycle by using the HasMiddleware trait and implementing the MiddlewareContract interface.

HTTP Kernel Request Processing with Middleware


Sources: src/Http/Kernel.php49-102 src/Http/Kernel.php78-82

Kernel Initialization

The Kernel class extends HyperfServer and implements the MiddlewareContract interface src/Http/Kernel.php28 using the HasMiddleware trait src/Http/Kernel.php30 to provide all middleware management functionality.

The initCoreMiddleware() method src/Http/Kernel.php32-39 initializes the kernel's middleware infrastructure:

  1. Sets the server name src/Http/Kernel.php34
  2. Creates the core middleware instance src/Http/Kernel.php35
  3. Initializes exception handlers src/Http/Kernel.php37
  4. Initializes HTTP server options src/Http/Kernel.php38

The initExceptionHandlers() method src/Http/Kernel.php41-47 configures exception handling by checking if a custom ExceptionHandlerContract is bound in the container src/Http/Kernel.php44 and if so, uses it; otherwise, falls back to the default ExceptionHandler class src/Http/Kernel.php46

Sources: src/Http/Kernel.php28-47

Middleware Execution Point

Middleware execution occurs in the onRequest() method src/Http/Kernel.php49-102 after several initialization steps:

  1. Worker Coordination: Waits for worker start src/Http/Kernel.php52
  2. Request/Response Initialization: Creates PSR-7 request and response objects src/Http/Kernel.php54
  3. Path Normalization: Trims trailing slashes from the URI path src/Http/Kernel.php57-62
  4. File Upload Conversion: Converts Hyperf UploadedFile instances to Hypervel's custom UploadedFile via convertUploadedFiles() src/Http/Kernel.php65-71
  5. Route Dispatching: Dispatches through core middleware to add routing information src/Http/Kernel.php74
  6. Event Dispatching: Fires RequestReceived event src/Http/Kernel.php73-76

Middleware Chain Execution occurs at src/Http/Kernel.php78-82:


The dispatcher receives:

  1. The PSR-7 request object with routing information
  2. Resolved and sorted middleware array from getMiddlewareForRequest()
  3. The core middleware for final route handler execution

After middleware execution:

Exception handling wraps the entire process via getResponseForException() src/Http/Kernel.php157-164 which uses Hyperf's SafeCaller to dispatch exceptions through the exception handler chain with a fallback to a 400 response.

Sources: src/Http/Kernel.php49-164

Configuration Example

A typical HTTP Kernel configuration extending the base Kernel class:


This configuration establishes:

  • Global middleware: Runs on all requests for proxy and CORS handling
  • Web group: Session, cookies, and CSRF protection for web routes
  • API group: Rate limiting and JSON response forcing for API routes
  • Aliases: Convenient shortcuts like auth, throttle, and can
  • Priority: Ensures proper execution order (CORS → Session → Auth → Throttle → CSRF)

Sources: src/Http/Traits/HasMiddleware.php17-49

Summary

The middleware system provides a flexible, performant mechanism for HTTP request filtering and processing through:

  • Multiple middleware types for different use cases (global, route, groups, aliases)
  • Intelligent resolution with group expansion and alias substitution
  • Priority-based ordering for deterministic execution sequences
  • Exclusion mechanism for fine-grained control
  • Aggressive caching to minimize resolution overhead
  • Comprehensive management API for runtime modification

The system is implemented primarily through the HasMiddleware trait src/Http/Traits/HasMiddleware.php which the Kernel class uses src/Http/Kernel.php28-30 to integrate with Hyperf's dispatcher and the broader HTTP request lifecycle.