VOOZH about

URL: https://deepwiki.com/hypervel/http/3-response-generation

⇱ Response Generation | hypervel/http | DeepWiki


Loading...
Menu

Response Generation

Purpose and Scope

This document provides an overview of the response generation system in Hypervel HTTP. It covers the Response class and ResponseContract interface, which provide a unified API for creating and manipulating HTTP responses. For detailed information about specific response types (JSON, views, files), see Response Types. For streaming and range request handling, see Streaming & Range Requests. For API resource transformations, see JSON Resources.

The response generation system abstracts the creation of PSR-7 compliant HTTP responses while providing convenient methods for common response patterns such as JSON APIs, file downloads, and server-sent events.

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

System Overview

The response generation subsystem is built on three foundational components:

  1. ResponseContract - Interface defining the public API for response creation
  2. Response - Concrete implementation extending Hyperf's response class
  3. StreamOutput - Helper class for managing chunked streaming responses

The Response class serves as the primary entry point for all response generation operations. It extends Hyperf\HttpServer\Response to inherit base functionality while adding Hypervel-specific features like view rendering, range request support, and enhanced streaming capabilities.

Sources: src/Response.php26 src/Contracts/ResponseContract.php12 src/StreamOutput.php9-20

Response Class Architecture

The following diagram shows how the Response class integrates with framework components and PSR standards:


Architecture Notes:

  • Response implements ResponseContract to define Hypervel's public API
  • Extends HyperfResponse to inherit base HTTP functionality
  • Leverages dependency injection to access framework services (views, filesystem, MIME detection)
  • Uses SwooleStream for response body content
  • Integrates with Swoole's native response object for streaming operations

Sources: src/Response.php26 src/Contracts/ResponseContract.php12 src/StreamOutput.php11-13

Core Response Methods

The Response class provides the following primary methods for response generation:

MethodPurposeReturnsSource
make()Create a generic response with automatic content-type detectionResponseInterfacesrc/Response.php162-184
json()Create a JSON response with proper headersResponseInterfacesrc/Response.php220-228
view()Render a view template and return as HTML responseResponseInterfacesrc/Response.php202-213
noContent()Create an empty response (typically 204)ResponseInterfacesrc/Response.php189-197
file()Serve a file with appropriate MIME typeResponseInterfacesrc/Response.php233-255
stream()Create a chunked streaming responseResponseInterfacesrc/Response.php271-314
streamDownload()Stream a file download with proper headersResponseInterfacesrc/Response.php323-339
withRangeHeaders()Enable HTTP range request supportstaticsrc/Response.php344-351
getPsr7Response()Access underlying PSR-7 responseResponseInterfacesrc/Response.php260-263

Sources: src/Response.php162-443 src/Contracts/ResponseContract.php14-77

Response Creation Flow

The following sequence diagram illustrates how different types of responses are created and processed:


Key Processing Steps:

  1. Content Detection: The make() method automatically detects content type based on the input (array, Jsonable, or scalar)
  2. Type Conversion: Arrays and objects are automatically JSON-encoded with appropriate headers
  3. View Rendering: The view() method delegates to Hyperf's RenderInterface for template processing
  4. File Serving: The file() method validates file existence, detects MIME type, and streams content
  5. PSR-7 Compliance: All methods return PSR-7 ResponseInterface instances for interoperability

Sources: src/Response.php162-255

HTTP Status Code Constants

The Response class defines comprehensive HTTP status code constants for use throughout the application:

RangeCategoryExample ConstantsSource
1xxInformationalHTTP_CONTINUE, HTTP_SWITCHING_PROTOCOLS, HTTP_PROCESSINGsrc/Response.php28-34
2xxSuccessHTTP_OK, HTTP_CREATED, HTTP_NO_CONTENT, HTTP_PARTIAL_CONTENTsrc/Response.php36-54
3xxRedirectionHTTP_MOVED_PERMANENTLY, HTTP_FOUND, HTTP_TEMPORARY_REDIRECTsrc/Response.php56-72
4xxClient ErrorHTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_UNPROCESSABLE_ENTITYsrc/Response.php74-130
5xxServer ErrorHTTP_INTERNAL_SERVER_ERROR, HTTP_SERVICE_UNAVAILABLEsrc/Response.php132-152

Usage Example:

Controllers can reference these constants when creating responses:


Notable Constants:

  • HTTP_PARTIAL_CONTENT (206) - Used for range requests
  • HTTP_NO_CONTENT (204) - Default for noContent() method
  • HTTP_UNPROCESSABLE_ENTITY (422) - Common for validation errors
  • HTTP_I_AM_A_TEAPOT (418) - RFC 2324 (included for completeness)

Sources: src/Response.php28-152

Context Management for Range Requests

The response system uses Hyperf's Context system to manage range request state across the request lifecycle:


Context Key: _response.withRangeHeaders (constant: RANGE_HEADERS_CONTEXT)

Methods:

  • withRangeHeaders(?int $fileSize) - Stores file size in context and enables range processing
  • withoutRangeHeaders() - Removes range context
  • shouldAppendRangeHeaders() - Checks if context is set
  • pullRangeHeaders() - Retrieves and clears context
  • appendRangeHeaders() - Processes Range header and sets appropriate response headers

Sources: src/Response.php157 src/Response.php344-423

Integration with Hyperf Components

The Response class integrates with several Hyperf framework services through dependency injection:


Service Resolution:

The Response class uses ApplicationContext::getContainer() to resolve dependencies on-demand rather than through constructor injection. This pattern is used in:

Context Usage:

Sources: src/Response.php204-250 src/Response.php389

Streaming Response Architecture

The streaming system enables chunked transfer encoding for large responses:


Streaming Process:

  1. Validation: Ensures response implements Chunkable interface src/Response.php274-276
  2. Header Setup: Sets Content-Type: text/event-stream if not specified src/Response.php282-284
  3. Range Support: Optionally appends range headers if enabled src/Response.php286-288
  4. Header Cleanup: Removes incompatible headers (Transfer-Encoding, Accept-Encoding, Content-Length) src/Response.php290-295
  5. Manual Send: Sends headers and status directly to Swoole response src/Response.php300-306
  6. Callback Execution: Invokes user callback with StreamOutput instance src/Response.php308-311

StreamOutput Helper:

The StreamOutput class wraps the Chunkable interface to provide a simple write() method for streaming content:

Sources: src/Response.php271-314 src/StreamOutput.php9-20

Response Contract Interface

The ResponseContract interface defines the complete public API for response generation:

Method SignaturePurpose
make(mixed $content, int $status, array $headers): ResponseInterfaceGeneral-purpose response factory
noContent(int $status, array $headers): ResponseInterfaceEmpty response with optional custom status
view(string $view, array $data, int $status, array $headers): ResponseInterfaceServer-side rendered view
json($data, int $status, array $headers): ResponseInterfaceJSON-encoded data response
file(string $path, array $headers): ResponseInterfaceFile serving with MIME detection
stream(callable $callback, array $headers): ResponseInterfaceChunked streaming response
streamDownload(callable $callback, ?string $filename, array $headers, string $disposition): ResponseInterfaceFile download streaming
withRangeHeaders(?int $fileSize): staticEnable range request support
withoutRangeHeaders(): staticDisable range request support
shouldAppendRangeHeaders(): boolCheck range request status
getPsr7Response(): ResponseInterfaceAccess underlying PSR-7 response

Interface Hierarchy:

The contract extends Hyperf\HttpServer\Contract\ResponseInterface, which in turn extends PSR-7's ResponseInterface. This multi-layer inheritance ensures:

  • Compatibility with PSR-7 middleware
  • Access to Hyperf's response utilities
  • Hypervel-specific enhancements

Sources: src/Contracts/ResponseContract.php12-77

Automatic Content-Type Detection

The make() method implements intelligent content-type detection based on the input type:


Detection Logic:

  1. Arrays/Arrayable: Automatically JSON-encoded with application/json content type src/Response.php168-171
  2. Jsonable Objects: Cast to string and treated as JSON src/Response.php173-176
  3. Explicit Header: If Content-Type already set, content is used as-is src/Response.php178-180
  4. Default: Plain text with text/plain content type src/Response.php182-183

This automatic detection simplifies response creation in controllers by eliminating the need to manually set content types for common scenarios.

Sources: src/Response.php162-184

Related Pages