VOOZH about

URL: https://deepwiki.com/hypervel/foundation/4.1-http-kernel-and-request-lifecycle

⇱ HTTP Kernel and Request Lifecycle | hypervel/foundation | DeepWiki


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

HTTP Kernel and Request Lifecycle

Purpose and Scope

This document details the HTTP Kernel's architecture and the complete request lifecycle from Swoole request reception through middleware processing to response emission. The Hypervel\Foundation\Http\Kernel class serves as the primary entry point for all HTTP requests in Hypervel applications, managing request initialization, middleware dispatch, event broadcasting, and exception handling.

For middleware-specific details, see Middleware System. For form request validation integration, see Form Request Validation. For exception handling implementation details, see Exception Handling and Error Responses.


HTTP Kernel Architecture

The HTTP Kernel extends Hyperf's HyperfServer class and implements the MiddlewareContract interface, providing a bridge between Swoole's HTTP server and the application's request handling logic.

Class Structure

ComponentTypePurpose
KernelClassMain HTTP server implementation
ParentHyperf\HttpServer\ServerHyperf's base HTTP server
InterfaceMiddlewareContractMiddleware configuration contract
TraitHasMiddlewareMiddleware management functionality

The kernel is responsible for:

  • Request and response object initialization
  • URI path normalization
  • Uploaded file conversion to Laravel-compatible format
  • Middleware pipeline coordination
  • Lifecycle event dispatching
  • Exception handling and recovery
  • Response emission to Swoole

Sources: src/Http/Kernel.php28-30


Request Lifecycle Overview

Diagram: Request Lifecycle Flow with Code Entities


Sources: src/Http/Kernel.php49-102


Request Lifecycle Phases

Phase 1: Worker Coordination

The kernel waits for the Swoole worker process to fully start before processing any requests. This ensures all services are properly initialized.


Sources: src/Http/Kernel.php52

Phase 2: Request and Response Initialization

The initRequestAndResponse() method (inherited from HyperfServer) creates PSR-7 compliant request and response objects from Swoole's native request and response objects.

Sources: src/Http/Kernel.php54

Phase 3: URI Path Normalization

All request URIs have trailing slashes removed, except for the root path /. This ensures consistent routing behavior.


Sources: src/Http/Kernel.php56-62

Phase 4: Uploaded File Conversion

Hyperf's UploadedFile instances are converted to Laravel-compatible Hypervel\Http\UploadedFile instances. This conversion happens recursively for nested file arrays.

The convertUploadedFiles() method:

  • Preserves null values and empty arrays
  • Recursively processes nested file arrays
  • Wraps each file with UploadedFile::createFromBase()
  • Updates the request context with converted files

Sources: src/Http/Kernel.php64-71 src/Http/Kernel.php110-121

Phase 5: Core Middleware Dispatch

The coreMiddleware->dispatch() method performs route matching and prepares the request with matched route parameters. This is distinct from the middleware pipeline execution that follows.

Sources: src/Http/Kernel.php74

Phase 6: Request Received Event

The RequestReceived event is dispatched after successful routing but before middleware execution. This event is only dispatched if request lifecycle events are enabled.

Event PropertyValue
requestThe matched request object
responseThe initial response object
serverServer name identifier

Sources: src/Http/Kernel.php73-76 src/Http/Kernel.php123-134

Phase 7: Middleware Pipeline Execution

The middleware dispatcher executes the complete middleware stack:

  1. Global middleware (all requests)
  2. Group middleware (route groups)
  3. Route-specific middleware
  4. Core middleware (final handler)

The getMiddlewareForRequest() method (from HasMiddleware trait) determines the appropriate middleware stack based on the request's matched route.

Sources: src/Http/Kernel.php78-82

Phase 8: Exception Handling

Any exception thrown during the request lifecycle is caught and converted to a response via getResponseForException(). This method:

  • Uses SafeCaller to safely invoke the exception handler
  • Falls back to a 400 status response if the handler itself fails
  • Dispatches the exception to the configured exception handlers

Sources: src/Http/Kernel.php83-84 src/Http/Kernel.php157-164

Phase 9: Request Handled and Terminated Events

Two events are dispatched after the response is generated:

  1. RequestHandled - Dispatched immediately with the final response
  2. RequestTerminated - Dispatched via defer() for deferred execution

Both events include the request, response, any exception that occurred, and the server name.

Sources: src/Http/Kernel.php86-89 src/Http/Kernel.php136-155

Phase 10: Response Emission

The response is emitted to the Swoole response object via responseEmitter->emit(). For HEAD requests, the response is emitted without the body.

Sources: src/Http/Kernel.php91-101


Detailed Sequence Diagram

Diagram: Request Lifecycle Method Call Sequence


Sources: src/Http/Kernel.php49-102


Kernel Initialization

The initCoreMiddleware() method is called during server startup to configure the kernel:

StepActionPurpose
1Set server nameIdentify which server instance
2Create core middlewareInitialize route dispatcher
3Initialize exception handlersSet up error handling chain
4Initialize optionsConfigure server behavior

Exception Handler Configuration

The kernel determines which exception handlers to use:

  • If ExceptionHandlerContract is bound in the container, use it
  • Otherwise, fall back to Hypervel\Foundation\Exceptions\Handler

This allows applications to provide custom exception handling implementations.

Sources: src/Http/Kernel.php32-39 src/Http/Kernel.php41-47


Uploaded File Conversion Algorithm

Diagram: File Conversion Process


Sources: src/Http/Kernel.php110-121


Event Lifecycle Configuration

Request lifecycle events can be enabled or disabled via the server options. The isEnableRequestLifecycle() method controls whether events are dispatched.

Available Events

EventTimingPurpose
RequestReceivedAfter routing, before middlewareSignal request entry
RequestHandledAfter response generatedAllow response modification
RequestTerminatedDeferred after response emissionPerform cleanup tasks

All events include:

  • request - The PSR-7 request object
  • response - The PSR-7 response object
  • server - Server name string
  • exception - Any thrown exception (for Handled/Terminated)

Sources: src/Http/Kernel.php125 src/Http/Kernel.php138


Integration with Form Request Validation

The FormRequestServiceProvider integrates with the request lifecycle by registering an afterResolving callback for ValidatesWhenResolved instances. When the dependency injection container resolves a form request, it automatically calls validateResolved() on the instance.

This integration happens through the RouteDependency service, which manages route-specific dependency resolution.

Sources: src/Providers/FormRequestServiceProvider.php16-22


Configuration

The HTTP Kernel's behavior is configured through the application configuration file. Key configuration values:

SettingPurposeDefault
app.debugEnable detailed error messagesfalse
app.envApplication environmentproduction
app.urlBase URL for URL generationhttp://localhost

Sources: publish/app.php36-93


Summary

The HTTP Kernel orchestrates the complete request lifecycle in Hypervel applications:

  1. Coordinates with Swoole worker startup
  2. Initializes PSR-7 request/response objects
  3. Normalizes URI paths for consistent routing
  4. Converts uploaded files to Laravel-compatible format
  5. Matches routes via core middleware dispatch
  6. Broadcasts request lifecycle events
  7. Executes middleware pipeline
  8. Handles exceptions with graceful recovery
  9. Emits responses back to Swoole

The kernel serves as the bridge between Swoole's low-level HTTP server and Hypervel's high-level application logic, ensuring a consistent and predictable request handling process while maintaining compatibility with Laravel's conventions.