VOOZH about

URL: https://deepwiki.com/hypervel/support/4-http-layer

⇱ HTTP Layer | hypervel/support | DeepWiki


Loading...
Menu

HTTP Layer

Purpose and Scope

The HTTP Layer provides comprehensive HTTP handling capabilities for both inbound and outbound HTTP operations. This includes receiving and processing HTTP requests, defining routes, validating input data, and making HTTP client requests to external services. The layer implements a Laravel-compatible API over Hyperf's high-performance HTTP foundation.

This document provides an overview of the HTTP Layer's architecture and components. For detailed information on specific subsystems, see:

Architectural Overview

The HTTP Layer consists of four primary subsystems that handle different aspects of HTTP operations:

SubsystemPrimary FacadePurposeContract/Accessor
Request HandlingRequestProcess incoming HTTP requests, access input data, headers, filesHypervel\Http\Contracts\RequestContract
RoutingRouteDefine routes, handle route dispatching, model bindingHypervel\Router\Router
ValidationValidatorValidate request input against rules, generate error messagesValidator contract
HTTP ClientHttpMake outbound HTTP requests, configure clients, handle responsesHTTP client factory

The HTTP Layer integrates with several other systems:

  • View Layer (#5): Routes return rendered views
  • Data Persistence (#6): Requests trigger database operations
  • Events (#7): HTTP operations dispatch events
  • Validation (#4.3): Requests validate input data

Sources: src/Facades/Request.php1-151 src/Facades/Route.php1-47

HTTP Request Processing Flow

The following diagram illustrates how an incoming HTTP request flows through the system, from the initial HTTP server receipt through route dispatching to the final response:


Key Components:

  • Hyperf\HttpServer: Underlying HTTP server that receives raw HTTP requests
  • RequestContract / RequestImpl: Wraps PSR-7 requests with convenience methods
  • Router: Matches request URI to defined routes
  • DispatchedRoute: Contains matched route information and parameters
  • Request Facade: Provides static API to access current request

Sources: src/Facades/Request.php1-151 src/Facades/Route.php1-47

Request Data Access Methods

The Request facade provides numerous methods for accessing different types of request data. These methods are organized by data source:

Input Data Methods

MethodReturn TypeDescription
Request::input($key, $default)mixedRetrieve input from query string, POST body, or JSON payload
Request::query($key, $default)mixedGet value from query string only
Request::post($key, $default)mixedGet value from POST body only
Request::all($keys)arrayGet all input data or specific keys
Request::only($keys)arrayGet subset of input data
Request::except($keys)arrayGet input data excluding specified keys
Request::collect($key)CollectionGet input as Collection instance

Type-Casted Input Methods

MethodReturn TypeDescription
Request::string($key, $default)StringableGet input as fluent string
Request::integer($key, $default)intGet input cast to integer
Request::float($key, $default)floatGet input cast to float
Request::boolean($key, $default)boolGet input as boolean
Request::date($key, $format, $tz)Carbon|nullParse input as Carbon date
Request::enum($key, $enumClass)object|nullParse input as enum instance

Request Metadata Methods

MethodReturn TypeDescription
Request::method()stringGet HTTP method (GET, POST, etc.)
Request::path()stringGet request path without query string
Request::url()stringGet full URL without query string
Request::fullUrl()stringGet full URL with query string
Request::ip()string|nullGet client IP address
Request::header($key, $default)string|nullGet request header value
Request::bearerToken()string|nullExtract Bearer token from Authorization header

Sources: src/Facades/Request.php10-103

Routing System Components

The routing system maps HTTP requests to application handlers through several interconnected components:


Route Definition Methods

MethodParametersDescription
Route::get($route, $handler, $options)URI pattern, handler, optionsDefine GET route
Route::post($route, $handler, $options)URI pattern, handler, optionsDefine POST route
Route::put($route, $handler, $options)URI pattern, handler, optionsDefine PUT route
Route::delete($route, $handler, $options)URI pattern, handler, optionsDefine DELETE route
Route::patch($route, $handler, $options)URI pattern, handler, optionsDefine PATCH route
Route::match($methods, $route, $handler, $options)HTTP methods array, URI, handler, optionsDefine route for multiple methods
Route::any($route, $handler, $options)URI pattern, handler, optionsDefine route for all HTTP methods

Route Organization Methods

MethodParametersDescription
Route::group($prefix, $callback, $options)URI prefix, definition callback, optionsGroup routes with shared attributes
Route::addServer($name, $callback)Server name, route definitionsDefine routes for specific server

Route Binding Methods

MethodParametersDescription
Route::model($param, $modelClass)Parameter name, model classAutomatically resolve model by ID
Route::bind($param, $callback)Parameter name, resolver closureCustom parameter resolution logic

Sources: src/Facades/Route.php10-35

Request Lifecycle Sequence

The following sequence diagram shows the complete lifecycle of an HTTP request, from initial receipt through validation to response generation:


Key Lifecycle Phases:

  1. Request Reception: Hyperf HTTP Server receives raw HTTP request and creates PSR-7 ServerRequestInterface
  2. Request Wrapping: Request is wrapped in Hypervel\Http\Request implementing RequestContract
  3. Route Matching: Router matches URI against registered routes using FastRoute
  4. Parameter Resolution: Route parameters are extracted; model binding occurs if configured
  5. Handler Invocation: Controller method or closure is invoked with resolved parameters
  6. Input Access: Controller retrieves input via Request::input(), Request::query(), etc.
  7. Validation: Optional validation via Request::validate() or Validator::make()
  8. Business Logic: Controller executes application logic, typically involving models
  9. Response Generation: Controller returns response (view, JSON, redirect, etc.)

Sources: src/Facades/Request.php76-93 src/Facades/Route.php18-21

Conditional Request Methods

The Request facade provides several methods for conditional input checking and processing:

Existence Checking

MethodDescription
Request::has($keys)Check if input contains key(s), even if empty string
Request::hasAny($keys)Check if any of the given keys exist
Request::filled($keys)Check if key exists and is not empty
Request::isNotFilled($key)Check if key is missing or empty
Request::anyFilled($keys)Check if any key is filled
Request::missing($key)Check if key does not exist in input
Request::exists($key)Alias for has()
Request::isEmptyString($key)Check if value is empty string

Conditional Callbacks

MethodSignatureDescription
Request::whenFilled($key, $callback, $default)Execute callback if key is filledReturns callback result or default
Request::whenHas($key, $callback, $default)Execute callback if key existsReturns callback result or default

Sources: src/Facades/Request.php17-49

Content Negotiation Methods

The Request object provides methods for content type negotiation, enabling applications to respond differently based on client preferences:

MethodReturn TypeDescription
Request::expectsJson()boolCheck if client expects JSON response
Request::wantsJson()boolCheck if client prefers JSON
Request::accepts($types)boolCheck if client accepts content type(s)
Request::acceptsJson()boolCheck if client accepts JSON
Request::acceptsHtml()boolCheck if client accepts HTML
Request::acceptsAnyContentType()boolCheck if client accepts any content type
Request::prefers($types)string|nullGet preferred content type from list
Request::getAcceptableContentTypes()string[]Get all accepted content types in order
Request::isJson()boolCheck if request payload is JSON
Request::ajax()boolCheck if request is XMLHttpRequest (AJAX)
Request::pjax()boolCheck if request is PJAX

Sources: src/Facades/Request.php41-72

URL and Path Methods

The Request facade provides comprehensive URL and path inspection capabilities:

Full URL Methods

MethodReturn TypeDescription
Request::url()stringGet URL without query string
Request::fullUrl()stringGet full URL with query string
Request::fullUrlWithQuery($query)stringGet URL with added query parameters
Request::fullUrlWithoutQuery($keys)stringGet URL excluding specific query parameters
Request::root()stringGet root URL (scheme + host)

Path Inspection

MethodReturn TypeDescription
Request::path()stringGet request path
Request::decodedPath()stringGet URL-decoded path
Request::segment($index, $default)string|nullGet specific path segment
Request::segments()arrayGet all path segments
Request::is(...$patterns)boolCheck if path matches pattern(s)
Request::routeIs(...$patterns)boolCheck if current route name matches
Request::fullUrlIs(...$patterns)boolCheck if full URL matches pattern(s)

Host and Scheme

MethodReturn TypeDescription
Request::getHost()stringGet hostname
Request::getHttpHost()stringGet host with port
Request::getScheme()stringGet scheme (http/https)
Request::getSchemeAndHttpHost()stringGet scheme + host + port
Request::isSecure()boolCheck if request is HTTPS
Request::getPort()int|stringGet port number

Sources: src/Facades/Request.php23-61 src/Facades/Request.php92-98

Route Information Access

The Request and Route facades provide methods to access information about the currently dispatched route:

Current Route Access

MethodReturn TypeDescription
Request::route($param, $default)DispatchedRoute|mixedGet DispatchedRoute or specific parameter
Request::getDispatchedRoute()DispatchedRouteGet current DispatchedRoute object
Route::current()DispatchedRoute|nullGet current route being handled
Route::getCurrentRoute()DispatchedRoute|nullAlias for current()
Route::currentRouteName()string|nullGet name of current route
Route::input($key, $default)mixedGet route parameter value

Named Route Management

MethodReturn TypeDescription
Route::has($name)boolCheck if named route exists
Route::getNamedRoutes()arrayGet all registered named routes

Sources: src/Facades/Request.php56-60 src/Facades/Route.php18-35

File Upload Handling

The Request facade provides methods for handling uploaded files through Hyperf's UploadedFile interface:

MethodReturn TypeDescription
Request::file($key, $default)UploadedFile|UploadedFile[]|nullGet uploaded file(s)
Request::hasFile($key)boolCheck if file was uploaded
Request::allFiles()arrayGet all uploaded files

The returned UploadedFile objects implement PSR-7's UploadedFileInterface, providing methods like:

  • getClientFilename(): Original filename
  • getClientMediaType(): MIME type
  • getSize(): File size in bytes
  • moveTo($targetPath): Move uploaded file to permanent location
  • getStream(): Get file stream for reading

Sources: src/Facades/Request.php10-105

PSR-7 Compatibility

The Request object maintains full PSR-7 compatibility, implementing ServerRequestInterface. This enables interoperability with PSR-7 middleware and libraries:

PSR-7 Methods

MethodInterfaceDescription
Request::getPsr7Request()CustomGet underlying PSR-7 request
Request::getServerParams()ServerRequestInterfaceGet server parameters
Request::getCookieParams()ServerRequestInterfaceGet cookie parameters
Request::getQueryParams()ServerRequestInterfaceGet query parameters
Request::getUploadedFiles()ServerRequestInterfaceGet uploaded files
Request::getParsedBody()ServerRequestInterfaceGet parsed body
Request::getAttributes()ServerRequestInterfaceGet request attributes
Request::getHeaders()MessageInterfaceGet all headers
Request::getBody()MessageInterfaceGet message body stream
Request::getProtocolVersion()MessageInterfaceGet HTTP protocol version

Immutable Modifier Methods

PSR-7 requires immutable request objects. The following methods return new instances:

  • Request::withHeader($name, $value)
  • Request::withAddedHeader($name, $value)
  • Request::withoutHeader($name)
  • Request::withBody($body)
  • Request::withProtocolVersion($version)
  • Request::withQueryParams($query)
  • Request::withCookieParams($cookies)
  • Request::withParsedBody($data)
  • Request::withAttribute($name, $value)
  • Request::withoutAttribute($name)

Sources: src/Facades/Request.php84-135

Request Mutation Methods

In addition to PSR-7's immutable methods, the Request object provides mutable methods for modifying input during processing:

MethodDescription
Request::merge($input)Merge new input into existing request data
Request::mergeIfMissing($input)Merge input only for missing keys
Request::replace($input)Replace all input data

These methods modify the current Request instance and return it for method chaining, unlike PSR-7's immutable pattern.

Sources: src/Facades/Request.php33-35

Integration with Other Systems

The HTTP Layer integrates closely with other Hypervel subsystems:

Session Integration

Request::hasSession() : bool
Request::session() : Session

Access the session associated with the current request. See Session documentation for details.

Authentication Integration

Request::user($guard = null) : mixed
Request::getUserResolver() : Closure
Request::setUserResolver($callback) : Request

Retrieve the authenticated user for the request. The user resolver can be customized for different authentication schemes.

Validation Integration

Request::validate($rules, $messages = [], $customAttributes = []) : array

Validate the request input inline. Throws ValidationException on failure. For detailed validation capabilities, see Validation.

URI Facade Integration

Request::uri() : Uri

Get a Hypervel\Support\Uri object for advanced URI manipulation. See URL Generation for details.

Sources: src/Facades/Request.php74-79

Signed URL Support

The Request facade provides methods for verifying signed URLs, which prevent tampering and ensure URLs were generated by the application:

MethodDescription
Request::hasValidSignature($absolute = true)Verify request has valid signature
Request::hasValidRelativeSignature()Verify signature without domain check
Request::hasValidSignatureWhileIgnoring($ignoreQuery, $absolute)Verify signature ignoring specific query parameters
Request::hasValidRelativeSignatureWhileIgnoring($ignoreQuery)Relative signature check with ignored parameters

Signed URLs are generated using the URL facade. See URL Generation for creating signed URLs.

Sources: src/Facades/Request.php80-83

Macro Support

Both Request and Route facades support macros, enabling custom method definitions:























MethodDescription
Request::macro($name, $macro)Register a custom macro
Request::mixin($mixin, $replace)Register all public methods from object as macros
Request::hasMacro($name)Check if macro is registered

Sources: src/Facades/Request.php137-139

Summary

The HTTP Layer provides a comprehensive, Laravel-compatible API for HTTP operations in Hyperf applications. Key capabilities include:

  • Request Processing: Access input data with type casting via the Request facade
  • Routing: Define routes with model binding via the Route facade
  • Validation: Validate input inline with Request::validate() or the Validator facade
  • HTTP Client: Make outbound HTTP requests with testing support
  • PSR-7 Compatible: Full PSR-7 ServerRequestInterface implementation
  • Content Negotiation: Detect client preferences for JSON, HTML, etc.
  • File Uploads: Handle uploaded files through PSR-7 UploadedFileInterface
  • Signed URLs: Verify URL signatures to prevent tampering
  • Extensible: Macro support for custom methods

For detailed information on each subsystem, refer to the child pages: Request Handling, Routing, Validation, and HTTP Client.

Sources: src/Facades/Request.php1-151 src/Facades/Route.php1-47

Refresh this wiki

On this page