VOOZH about

URL: https://deepwiki.com/hypervel/http/3.1-response-object-and-contract

⇱ Response Object & Contract | hypervel/http | DeepWiki


Loading...
Menu

Response Object & Contract

Purpose and Scope

This document covers the Response class and ResponseContract interface, which form the foundation of HTTP response generation in Hypervel. These components provide a fluent API for creating responses with status codes, headers, and content, while maintaining compatibility with PSR-7 standards and the Hyperf framework.

For information about specific response types (JSON, views, files, downloads), see Response Types. For streaming responses and range request handling, see Streaming & Range Requests. For JSON resource transformations, see JSON Resources.

Sources: src/Response.php1-443 src/Contracts/ResponseContract.php1-78


Architecture and Class Hierarchy

The response system follows a contract-based architecture where ResponseContract defines the public API and Response provides the concrete implementation. This design enables dependency injection and testability while extending Hyperf's base functionality.

Class Hierarchy Diagram


Sources: src/Response.php26 src/Contracts/ResponseContract.php12


HTTP Status Code Constants

The Response class defines comprehensive HTTP status code constants covering all standard codes from informational (1xx) to server error (5xx) responses. These constants improve code readability and reduce magic numbers.

Status Code Categories

CategoryRangeConstants AvailableExample Constants
Informational1xx4HTTP_CONTINUE, HTTP_SWITCHING_PROTOCOLS, HTTP_PROCESSING, HTTP_EARLY_HINTS
Successful2xx8HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, HTTP_NO_CONTENT, HTTP_PARTIAL_CONTENT
Redirection3xx8HTTP_MOVED_PERMANENTLY, HTTP_FOUND, HTTP_SEE_OTHER, HTTP_NOT_MODIFIED, HTTP_TEMPORARY_REDIRECT
Client Error4xx19HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_UNPROCESSABLE_ENTITY
Server Error5xx8HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_SERVICE_UNAVAILABLE, HTTP_GATEWAY_TIMEOUT

Complete Status Code List


Notable Status Codes:

  • HTTP_I_AM_A_TEAPOT (418): RFC 2324 joke status code
  • HTTP_PARTIAL_CONTENT (206): Used for range request responses
  • HTTP_UNPROCESSABLE_ENTITY (422): Common for validation errors (RFC 4918)
  • HTTP_TOO_MANY_REQUESTS (429): Rate limiting (RFC 6585)

Sources: src/Response.php28-152


ResponseContract Interface

The ResponseContract interface defines the public API for response generation. It extends HyperfResponseInterface to maintain compatibility with the Hyperf framework while adding Hypervel-specific functionality.

Method Categories


Interface Method Signatures

MethodParametersReturn TypePurpose
make()mixed $content, int $status = 200, array $headers = []ResponseInterfaceCreate general-purpose response with automatic content type detection
noContent()int $status = 204, array $headers = []ResponseInterfaceCreate empty response for operations with no content
view()string $view, array $data = [], int $status = 200, array $headers = []ResponseInterfaceRender template and return HTML response
json()`arrayArrayableJsonable $data, int $status = 200, array $headers = []`
file()string $path, array $headers = []ResponseInterfaceReturn file contents with MIME type detection
stream()callable $callback, array $headers = []ResponseInterfaceCreate chunked streaming response
streamDownload()callable $callback, ?string $filename, array $headers = [], string $disposition = 'attachment'ResponseInterfaceStream file download with proper headers
withRangeHeaders()?int $fileSize = nullstaticEnable HTTP range request support
withoutRangeHeaders()-staticDisable HTTP range request support
shouldAppendRangeHeaders()-boolCheck if range headers should be added
getPsr7Response()-ResponseInterfaceGet underlying PSR-7 response object

Sources: src/Contracts/ResponseContract.php12-77


Response Class Implementation

The Response class implements ResponseContract and extends Hyperf's HyperfResponse base class, providing the concrete implementation of response generation while maintaining framework integration.

Component Integration


Sources: src/Response.php1-25 src/Response.php26


Basic Response Creation

The Response class provides two fundamental methods for creating HTTP responses: make() for general-purpose responses and noContent() for empty responses.

make() Method

The make() method automatically detects content type and creates appropriate responses based on the content provided.

Method Flow:


Content Type Detection Logic:

Content TypeConditionContent-Type HeaderBody Encoding
Array/Arrayableis_array($content) or $content instanceof Arrayableapplication/jsonJson::encode($content)
Jsonable$content instanceof Jsonableapplication/json(string) $content
Pre-setHeader already existsExisting value(string) $content
DefaultNone of abovetext/plain(string) $content

Sources: src/Response.php162-184

noContent() Method

The noContent() method creates responses with no body content, typically used for DELETE operations or successful actions that don't return data.

Implementation Details:

  • Default status code: 204 No Content
  • No response body created
  • Only status code and headers are set
  • Returns empty ResponseInterface

Common Use Cases:

Status CodeUse Case
204Successful DELETE operation
204Successful PUT with no response data
304Not Modified (cache validation)
205Reset Content (clear form after submission)

Sources: src/Response.php189-197


Response Creation Example Flow

The following diagram shows how different content types are processed when creating responses:


Sources: src/Response.php162-197


PSR-7 Integration

The Response class maintains full PSR-7 compatibility while providing a more convenient API than working directly with PSR-7 response objects.

Accessing PSR-7 Response

The getPsr7Response() method provides direct access to the underlying PSR-7 ResponseInterface object for cases where low-level manipulation is needed.

Method Signature:


Implementation:

Returns: $this->getResponse()

Use Cases:

ScenarioWhy Access PSR-7 Directly
Third-party middlewareMiddleware expecting PSR-7 ResponseInterface
Custom header manipulationDirect PSR-7 methods like withHeader(), withAddedHeader()
Protocol-level operationsSetting protocol version, reason phrase
TestingAsserting low-level response properties

Sources: src/Response.php260-263


Context Management for Range Headers

The Response class uses Hyperf's context system to manage range header state during request processing, enabling HTTP partial content delivery.

Range Header Context Flow


Context Constants

ConstantValuePurpose
RANGE_HEADERS_CONTEXT'_response.withRangeHeaders'Context key for range header configuration

Range Header Methods

MethodReturn TypeSide Effect
withRangeHeaders(?int $fileSize = null)staticStores range config in context, returns $this for chaining
withoutRangeHeaders()staticRemoves range config from context, returns $this for chaining
shouldAppendRangeHeaders()boolChecks if context key exists

Sources: src/Response.php157 src/Response.php344-369 src/Response.php374-381 src/Response.php386-423


Dependency Injection and Instantiation

The Response class is registered in the dependency injection container through the ConfigProvider and can be accessed via contract binding.

DI Registration Pattern


Usage in Controllers

Type-Hinting:


Manual Resolution:


Sources: src/Contracts/ResponseContract.php5 src/Response.php26


StreamOutput Helper Class

The StreamOutput class provides a clean API for writing content during streaming responses, wrapping the underlying Chunkable interface.

Class Structure


StreamOutput API

MethodParametersReturn TypeDescription
__construct()Chunkable $chunkable-Initialize with chunkable response
write()string $contentboolWrite chunk to response stream

Usage in Callbacks:


Sources: src/StreamOutput.php1-21


Summary

The Response class and ResponseContract interface provide a comprehensive, fluent API for HTTP response generation in Hypervel. Key features include:

  • HTTP Status Constants: Complete set of standard status codes (100-511)
  • Contract-Based Design: Interface-driven architecture for testability
  • Automatic Content Detection: Smart content-type handling in make()
  • PSR-7 Compatibility: Full interoperability with PSR-7 middleware
  • Context Management: Request-scoped state for range headers
  • Framework Integration: Seamless integration with Hyperf DI and services

The response system serves as the foundation for more specialized response types documented in Response Types, streaming capabilities in Streaming & Range Requests, and API response formatting in JSON Resources.

Sources: src/Response.php1-443 src/Contracts/ResponseContract.php1-78 src/StreamOutput.php1-21