VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/3.3-request-macros-and-extensions

⇱ Request Macros and Extensions | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Request Macros and Extensions

This document describes the request macro system that extends Hyperf's RequestInterface with 40+ Laravel-style convenience methods for data retrieval, validation, and request inspection. These macros are implemented in the RequestMixin class and automatically registered via the Macroable trait pattern.

For general helper functions including request(), see Global Helper Functions. For validation specifics, see Validated DTOs and Type Casting.

Purpose and Architecture

The request macro system enhances Hyperf's PSR-7 request implementation with a rich set of convenience methods that simplify common request handling tasks. The system uses PHP's __call magic method via the Macroable trait to dynamically add methods to the Request class without modifying its source code.

Diagram: Request Macro Registration and Invocation Flow


Sources: src/macros/src/RequestMixin.php1-386 tests/TestCase.php28-31

Registration Mechanism

The macro registration occurs during application bootstrap through an event listener that processes all mixin definitions.

Diagram: Mixin Registration Process


The RegisterMixinListener is invoked during the BootApplication event and calls Request::mixin(new RequestMixin()), which registers all public methods from the mixin class as macros on the target class.

Sources: tests/TestCase.php28-31 src/macros/src/RequestMixin.php36

Method Categories Overview

The request macros are organized into functional categories based on their purpose:

CategoryMethodsPurpose
Data Retrievalcollect(), fluent(), only(), except(), allFiles()Extract data from request in various formats
Type Castingboolean(), integer(), float(), string(), str(), date(), enum()Retrieve input with automatic type conversion
Validationfilled(), isNotFilled(), anyFilled(), missing(), exists(), hasAny(), isEmptyString()Check presence and validity of input
Request InspectionwantsJson(), isJson(), isSecure(), getHost(), getPort(), getScheme(), httpHost(), schemeAndHttpHost()Inspect request properties
Data Manipulationmerge(), mergeIfMissing(), keys()Modify request data
Conditional ExecutionwhenFilled(), whenHas()Execute callbacks conditionally
Validation Integrationvalidate(), validateWithBag()Perform validation on request data
Testingfake(), getPsrRequest()Create test requests and access PSR-7 object

Sources: src/macros/src/RequestMixin.php1-386 src/macros/output/Hyperf/HttpServer/Contract/RequestInterface.php18-224

Data Retrieval and Type Casting Methods

These methods provide convenient ways to extract and convert request data into the desired types.

Diagram: Data Retrieval Method Flow


Collection Methods

collect($key = null) - Returns request data as a Hyperf\Collection\Collection instance:

  • Without arguments: returns all request data as a collection
  • With a string key: returns the value for that key wrapped in a collection
  • With an array of keys: returns a collection containing only those keys

Sources: src/macros/src/RequestMixin.php63-74

fluent($key = null) - Returns request data as a Hyperf\Support\Fluent object for property-style access:


Sources: src/macros/src/RequestMixin.php150-155

only($keys) - Retrieves only specified keys from request data, supporting dot notation:

Sources: src/macros/src/RequestMixin.php287-304 tests/Macros/HttpServerRequestTest.php23-34

except($keys) - Returns all request data except specified keys:

Sources: src/macros/src/RequestMixin.php108-118

Type Casting Methods

boolean($key, $default = false) - Converts input to boolean using FILTER_VALIDATE_BOOLEAN, treating "1", "true", "on", and "yes" as true:

Sources: src/macros/src/RequestMixin.php58-61

integer($key, $default = null) - Casts input to integer:

Sources: src/macros/src/RequestMixin.php225-228

float($key, $default = null) - Casts input to float:

Sources: src/macros/src/RequestMixin.php145-148

string($key, $default = null) / str($key, $default = null) - Returns input as a Hyperf\Stringable\Stringable instance:

Sources: src/macros/src/RequestMixin.php316-324

date($key, $format = null, $tz = null) - Parses input as a Carbon date:

  • With format: uses Carbon::createFromFormat()
  • Without format: uses Carbon::parse()
  • Returns null if key is not filled

Sources: src/macros/src/RequestMixin.php76-89

enum($key, $enumClass) - Converts input to a backed enum instance using tryFrom():

Sources: src/macros/src/RequestMixin.php91-106

File Methods

allFiles() - Returns all uploaded files from the request:

Sources: src/macros/src/RequestMixin.php38-41

Validation and Presence Checking Methods

These methods provide granular control over checking input presence and emptiness.

Diagram: Validation Method Decision Tree


Sources: src/macros/src/RequestMixin.php44-160 tests/Macros/HttpServerRequestTest.php36-47

Presence Methods

exists($key) / has($key) - Checks if a key exists in the request, regardless of its value:

Sources: src/macros/src/RequestMixin.php120-123

missing($key) - Returns true if key is absent from the request (inverse of has()):

Sources: src/macros/src/RequestMixin.php282-285

hasAny($keys) - Checks if any of the specified keys exist:

Sources: src/macros/src/RequestMixin.php157-160

Filled State Methods

filled($key) - Returns true if the key exists and is not an empty string. Accepts single key or array:


Sources: src/macros/src/RequestMixin.php130-143

isNotFilled($key) - Inverse of filled(), returns true if key is absent or is an empty string:

Sources: src/macros/src/RequestMixin.php244-257

anyFilled($keys) - Returns true if at least one of the specified keys is filled:

Sources: src/macros/src/RequestMixin.php43-56

isEmptyString($key) - Checks if a value is an empty string (after trimming), excluding booleans and arrays:

Sources: src/macros/src/RequestMixin.php230-237 tests/Macros/HttpServerRequestTest.php36-47

Request Inspection Methods

These methods provide information about the request itself, including host, port, scheme, and content type.

Diagram: Request Property Extraction


Sources: src/macros/src/RequestMixin.php162-333 tests/Macros/HttpServerRequestTest.php49-152

Host and Port Methods

getHost() / host() - Extracts the hostname from the request, checking in order:

  1. HOST header
  2. SERVER_NAME server parameter
  3. SERVER_ADDR server parameter

The method strips port numbers and converts to lowercase.

Sources: src/macros/src/RequestMixin.php162-178 tests/Macros/HttpServerRequestTest.php49-76

getPort() - Determines the port number from the HOST header or SERVER_PORT, defaulting to 80 for HTTP or 443 for HTTPS:

Sources: src/macros/src/RequestMixin.php190-209 tests/Macros/HttpServerRequestTest.php78-114

getHttpHost() / httpHost() - Returns host:port combination:

Sources: src/macros/src/RequestMixin.php167-183

getScheme() - Returns 'https' or 'http' based on isSecure():

Sources: src/macros/src/RequestMixin.php211-214 tests/Macros/HttpServerRequestTest.php116-132

isSecure() - Checks if HTTPS server parameter is set and not 'off':

Sources: src/macros/src/RequestMixin.php216-223

getSchemeAndHttpHost() / schemeAndHttpHost() - Returns the full scheme, host, and port (e.g., https://example.com:443):

Sources: src/macros/src/RequestMixin.php306-314

Content Type Methods

wantsJson() - Checks if the first Accept header contains '/json' or '+json':

Sources: src/macros/src/RequestMixin.php326-333 tests/Macros/HttpServerRequestTest.php134-152

isJson() - Checks if the Content-Type header contains '/json' or '+json':

Sources: src/macros/src/RequestMixin.php239-242

Data Manipulation Methods

These methods allow runtime modification of request data stored in the Hyperf context.

Diagram: Request Data Mutation Flow


Sources: src/macros/src/RequestMixin.php259-285

Merge Methods

merge(array $input) - Merges new data into the request, overriding existing keys. Uses Context::override() to modify the parsed data in the coroutine context:


Sources: src/macros/src/RequestMixin.php264-271

mergeIfMissing(array $input) - Merges data only for keys that don't exist in the request:


Sources: src/macros/src/RequestMixin.php273-280

Keys Method

keys() - Returns an array of all input and file keys from the request:

Sources: src/macros/src/RequestMixin.php259-262

Conditional Execution Methods

These methods enable fluent conditional logic based on input presence.

Diagram: Conditional Method Execution


Sources: src/macros/src/RequestMixin.php335-363

whenFilled Method

whenFilled($key, callable $callback, ?callable $default = null) - Executes the callback if the key is filled (present and non-empty):


Returns the result of the callback, or $this for chaining if callback returns null.

Sources: src/macros/src/RequestMixin.php335-348

whenHas Method

whenHas($key, callable $callback, ?callable $default = null) - Executes the callback if the key exists (regardless of value):


Sources: src/macros/src/RequestMixin.php350-363

Validation Integration

The request macros integrate with Hyperf's validation system to provide convenient inline validation.

Diagram: Validation Integration


Sources: src/macros/src/RequestMixin.php365-385

validate Method

validate(array $rules, ...$params) - Validates request data and returns validated data on success, throws ValidationException on failure:


Retrieves ValidatorFactoryInterface from the container, creates a validator with all request data, and runs validation.

Sources: src/macros/src/RequestMixin.php365-374

validateWithBag Method

validateWithBag($errorBag, $rules, ...$params) - Validates data and associates validation errors with a named error bag:


Sources: src/macros/src/RequestMixin.php376-385

Testing Utilities

The request macros provide utilities for creating fake requests in tests.

Diagram: Test Request Creation


Sources: src/macros/src/RequestMixin.php125-128 tests/Macros/HttpServerRequestTest.php154-170

fake Method

Request::fake(?Closure $closure = null) - Static method that creates a fake ServerRequest instance for testing:


The optional closure receives the base ServerRequest and can modify it using PSR-7 methods. The fake request can be set in the context for use with the Request class:


Sources: src/macros/src/RequestMixin.php125-128 tests/Macros/HttpServerRequestTest.php154-170

getPsrRequest Method

getPsrRequest() - Returns the underlying PSR-7 ServerRequestInterface from the context, or null if not set:


Sources: src/macros/src/RequestMixin.php185-188 tests/Macros/HttpServerRequestTest.php172-179

Integration with Helper Functions

The request macros integrate with global helper functions to provide multiple access patterns.

Table: Request Access Patterns

PatternExampleReturnsSource
Helper functionrequest()RequestInterface instancesrc/helpers/src/Functions.php462-475
Helper with keyrequest('name')Input value for keysrc/helpers/src/Functions.php462-475
Helper with arrayrequest(['name', 'email'])Array of valuessrc/helpers/src/Functions.php462-475
Dependency injectiondi(RequestInterface::class)RequestInterface instancesrc/helpers/src/Functions.php169-191
Macro methodrequest()->string('name')Stringable instancesrc/macros/src/RequestMixin.php316-324
Chained macrosrequest()->whenFilled('email', fn($e) => ...)$this or callback resultsrc/macros/src/RequestMixin.php335-348

Sources: src/helpers/src/Functions.php462-475 src/macros/src/RequestMixin.php1-386

Implementation Details and Context Management

The request macros use Hyperf's coroutine context system to store and retrieve request data.

Table: Context Keys Used by Request Macros

Context KeyPurposeUsed ByType
ServerRequestInterface::classStores PSR-7 requestgetPsrRequest(), getHost(), getPort()ServerRequestInterface
contextkeys['parsedData']Stores merged input datamerge(), mergeIfMissing()Array
RequestContextHyperf's request context wrapperVarious request methodsContext wrapper

The merge() and mergeIfMissing() methods use Context::override() to atomically modify the parsed data array in the coroutine-local context, ensuring thread safety in Swoole's coroutine environment.

Sources: src/macros/src/RequestMixin.php264-280 src/macros/src/RequestMixin.php185-188

Mixin Property Access

The RequestMixin class defines a @property annotation for contextkeys, which is accessed by the merge() method to retrieve the context key for parsed data:


This property is defined on the target Request class and provides the mapping between conceptual data locations and their context keys.

Sources: src/macros/src/RequestMixin.php33-34 src/macros/src/RequestMixin.php267