VOOZH about

URL: https://deepwiki.com/hypervel/http/4.1-core-middleware-and-request-lifecycle

⇱ Core Middleware & Request Lifecycle | hypervel/http | DeepWiki


Loading...
Menu

Core Middleware & Request Lifecycle

Purpose and Scope

This document details how CoreMiddleware orchestrates the complete HTTP request lifecycle in the hypervel/http package. It explains the dispatching process, route status handling, dependency injection integration, and response transformation mechanisms that convert controller return values into standard HTTP responses.

For information about route dependency injection and parameter resolution, see Route Dependency Injection. For CORS and validation middleware, see CORS Middleware and Request Validation Middleware.

Request Lifecycle Overview

The CoreMiddleware class implements CoreMiddlewareInterface and serves as the central orchestrator for processing HTTP requests. It bridges the routing system, dependency injection, and response generation.

Complete Request Flow


Sources: src/CoreMiddleware.php111-181

CoreMiddleware Construction

The CoreMiddleware is instantiated with container access and a server name:

PropertyTypePurpose
$containerContainerInterfaceDI container for resolving services
$serverNamestringIdentifies which HTTP server this middleware serves
$dispatcherDispatcherFastRoute dispatcher for route matching
$routeDependencyRouteDependencyHandles parameter injection for routes

The constructor initializes the FastRoute dispatcher via DispatcherFactory and retrieves the RouteDependency instance from the container.

Sources: src/CoreMiddleware.php34-46

Dispatch Process

Route Dispatching

The dispatch() method performs the initial route matching:


The dispatch() method:

  1. Calls the FastRoute Dispatcher::dispatch() with HTTP method and URI path
  2. Wraps the result in a DispatchedRoute object
  3. Stores the request in RequestContext
  4. Attaches the DispatchedRoute to the request as an attribute

Sources: src/CoreMiddleware.php111-120

DispatchedRoute Properties

The DispatchedRoute extends Hyperf's base Dispatched class and provides access to:

MethodReturn TypeDescription
getHandler()?RouteHandlerThe matched route handler
isClosure()boolWhether handler is a closure
isControllerAction()boolWhether handler is a controller method
getCallback()array|callable|stringThe invokable callback
parameters()arrayRoute parameters from URI
getName()?stringNamed route identifier
getMiddleware()arrayRoute-specific middleware
getControllerClass()?stringFully qualified controller class name
getControllerCallback()array[controller, action] tuple

Sources: src/DispatchedRoute.php1-108

Request Processing

Main Processing Logic

The process() method is the PSR-15 middleware entry point:


The process:

  1. Sets the request in RequestContext for global access
  2. Retrieves the DispatchedRoute from request attributes
  3. Validates the dispatched object type
  4. Uses a match expression to handle status codes
  5. Transforms non-standard responses to ResponsePlusInterface
  6. Adds the Server: Hypervel header

Sources: src/CoreMiddleware.php158-181

Route Status Handling

Found Routes

When status === Dispatcher::FOUND, the handleFound() method executes the route handler:


For closure routes:

  1. RouteDependency::getClosureParameters() resolves dependencies
  2. After-resolving callbacks are fired (see Route Dependency Injection)
  3. Closure is invoked with resolved parameters

For controller routes:

  1. Parse [controller, action] tuple via getControllerCallback()
  2. Resolve controller instance from container
  3. Verify the action method exists (throws ServerErrorHttpException if not)
  4. RouteDependency::getMethodParameters() resolves dependencies
  5. Fire after-resolving callbacks
  6. If controller has callAction() method, use it; otherwise invoke action directly

Sources: src/CoreMiddleware.php127-152

Not Found Routes

When status === Dispatcher::NOT_FOUND, the handleNotFound() method throws:


This exception should be caught by exception handling middleware to return a 404 response.

Sources: src/CoreMiddleware.php186-189

Method Not Allowed Routes

When status === Dispatcher::METHOD_NOT_ALLOWED, the handleMethodNotAllowed() method:

  1. Extracts allowed methods from $dispatched->params
  2. Formats them as comma-separated string
  3. For OPTIONS requests, returns a response with Allow header
  4. For other methods, throws MethodNotAllowedHttpException with allowed methods message

Sources: src/CoreMiddleware.php194-203

Response Transformation

Supported Return Types

The transferToResponse() method converts various controller return types into a standard ResponsePlusInterface:


Transformation Rules

Return TypeContent-TypeProcessing
Renderable (View)From RenderInterface::getContentType()Calls render() method, optionally dispatches ViewRendered event
stringtext/plainDirect body content
ResponseInterfacePreservedWrapped in ResponsePlusProxy
array or Arrayableapplication/jsonEncoded via Json::encode()
Jsonableapplication/jsonCast to string via __toString()
Other (with existing content-type)PreservedCast to string
Other (no content-type)text/plainCast to string

View Rendering: When a ViewInterface is returned and view.event.enable config is true, the middleware dispatches a ViewRendered event before rendering.

Sources: src/CoreMiddleware.php53-95

Integration with RouteDependency

The CoreMiddleware delegates parameter resolution to the RouteDependency service:

Dependency Resolution Flow


Parameter Resolution Priority

For each parameter in the method/closure signature, RouteDependency resolves values in this order:

  1. Route Parameter (by index or name): From $route->parameters()
  2. Default Value: If parameter has default value available
  3. Container Resolution: If container has binding for parameter type
  4. Null: If parameter is nullable
  5. Exception: If none of above apply, throws InvalidArgumentException

Values from route parameters are denormalized to the correct type using NormalizerInterface.

Sources: src/CoreMiddleware.php130-144 src/RouteDependency.php106-173

After-Resolving Callbacks

After parameters are resolved, fireAfterResolvingCallbacks() is invoked:

  1. Iterates through all resolved parameter instances
  2. For each object instance, retrieves matching callbacks via getAfterResolvingCallbacks()
  3. Executes callbacks with signature: callable($dependency, DispatchedRoute $dispatched)

This allows for post-resolution logic like logging, validation, or modification of resolved dependencies. See Route Dependency Injection for details on registering these callbacks.

Sources: src/CoreMiddleware.php131-144 src/RouteDependency.php65-79

Context Management

Request and Response Context

The CoreMiddleware interacts with two context systems:

RequestContext: Stores the current ServerRequestInterface in context-local storage:

  • RequestContext::set($request) stores the request
  • Makes request globally accessible within the same coroutine/request lifecycle

ResponseContext: Provides access to the response being built:

  • ResponseContext::get() retrieves the response instance
  • Used by response() helper method throughout the middleware

The process() method explicitly sets the request context at line 160, ensuring the request is available to all subsequent processing.

Sources: src/CoreMiddleware.php9-160

Error Handling

Exception Types

The middleware throws specific HTTP exceptions:

ExceptionStatusThrown When
NotFoundHttpException404Route not found (Dispatcher::NOT_FOUND)
MethodNotAllowedHttpException405Route exists but method not allowed
ServerErrorHttpException500Controller action method doesn't exist
ServerException500Dispatched object is invalid type

All HTTP exceptions should be caught by exception handling middleware higher in the stack to generate appropriate error responses.

Sources: src/CoreMiddleware.php140-202

Response Header Injection

Every response generated by the middleware receives a Server: Hypervel header before being returned. This branding header is added at the final step of the process() method regardless of the route status or response type.

Sources: src/CoreMiddleware.php180