VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/3-core-utilities-and-helper-functions

⇱ Core Utilities and Helper Functions | friendsofhyperf/components | DeepWiki


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

Core Utilities and Helper Functions

This document provides an overview of the core utility functions and request extensions that offer Laravel-style convenience APIs for Hyperf applications. These utilities are foundational components used throughout the monorepo to simplify dependency injection, request handling, data transformation, and resource access.

For information about the dispatch helper that routes jobs to different queue backends, see Fluent Dispatch API and Job Routing. For detailed coverage of individual helper functions, see Global Helper Functions. For comprehensive request macro documentation, see Request Macros and Extensions.

System Architecture

The utilities layer consists of two primary components: global helper functions that provide Laravel-style convenience methods, and request macros that extend Hyperf's RequestInterface with additional functionality. These are integrated via the ConfigProvider registration system and RegisterMixinListener for runtime mixin attachment.


Sources: src/helpers/src/Functions.php1-682 src/macros/src/RequestMixin.php1-387 tests/TestCase.php27-34

Helper Function Categories

The helpers library provides functions organized into five main categories, each serving distinct purposes within the application architecture.

CategoryFunctionsPurpose
Container Accessapp(), di(), resolve()Retrieve services from DI container with type safety
Resource Accesscache(), logger(), logs(), request(), response(), session(), cookie()Access framework resources with optional value setting
Data Transformationtransform(), rescue(), enum_value(), object_get(), fluent(), literal()Transform and safely access data structures
Validationblank(), filled(), throw_if(), throw_unless(), validator()Check values and validate input
Utilitiesclass_namespace(), preg_replace_array(), get_client_ip(), base_path(), event()Miscellaneous helper operations

Sources: src/helpers/src/Functions.php59-682

Container and Dependency Injection Pattern

The container helpers provide unified access to the Hyperf dependency injection system with support for both service retrieval and on-demand instantiation. The pattern checks for container availability and falls back to direct instantiation when needed.


Sources: src/helpers/src/Functions.php68-191

Request Macro Registration System

Request macros are registered at application boot via the RegisterMixinListener, which uses Hyperf's Macroable trait to dynamically add methods to the Request class. This pattern allows extending the request interface without modifying core framework classes.


Sources: tests/TestCase.php29-31 src/macros/src/RequestMixin.php32-386

Request Macro Method Categories

The request macros extend the base RequestInterface with 40+ convenience methods organized into functional groups. Each method is implemented as a closure that binds to the request instance at runtime.

CategoryMethodsFunctionality
Input Retrievalcollect(), only(), except(), keys()Access request data as collections or subsets
Type Castingboolean(), integer(), float(), string(), date(), enum()Cast input values to specific types
Validationfilled(), isNotFilled(), anyFilled(), exists(), missing(), hasAny()Check presence and emptiness of inputs
ConditionalwhenFilled(), whenHas()Execute callbacks based on input presence
Fluent Objectsfluent(), str()Convert inputs to fluent wrapper objects
Validationvalidate(), validateWithBag()Validate request data inline
Request Infohost(), httpHost(), getPort(), getScheme(), isSecure(), wantsJson(), isJson()Access request metadata
Manipulationmerge(), mergeIfMissing()Modify request input data

Sources: src/macros/src/RequestMixin.php38-386 src/macros/output/Hyperf/HttpServer/Contract/RequestInterface.php19-224

Data Transformation Pipeline

The data transformation utilities provide a functional programming approach to handling nullable values and error conditions. The transform() function applies callbacks only to filled values, while rescue() catches exceptions and returns fallback values.


Sources: src/helpers/src/Functions.php622-645 src/helpers/src/Functions.php510-531

Fluent Object Pattern

The fluent object helpers (fluent() and literal()) provide dynamic object creation with property access. The fluent() function wraps arrays/objects in Hyperf\Support\Fluent for method chaining, while literal() creates anonymous objects using named arguments.

Fluent vs Literal Comparison

Featurefluent($value)literal(...$arguments)
InputArray or objectNamed arguments
Return TypeHyperf\Support\FluentstdClass
Property Access$obj->get('key') and $obj->key$obj->key only
Method ChainingSupports chainable methodsNo methods
Use CaseDynamic method calls, toArray()Simple data structures

Sources: src/helpers/src/Functions.php294-338 tests/Helpers/HelpersTest.php106-110

Resource Access Pattern

Resource helper functions follow a consistent pattern: when called without arguments, they return the service instance; when called with arguments, they perform operations on the service. This dual behavior provides both direct service access and convenience shortcuts.

Resource Helper Behaviors

FunctionNo ArgumentsWith Arguments
cache()Returns CacheInterfacecache('key') gets value, cache(['key' => 'val']) sets value
logger()Returns LoggerInterfacelogger('message', $context) logs debug message
request()Returns RequestInterfacerequest('key') gets input, request(['key1', 'key2']) gets multiple
response()Returns ResponseInterfaceresponse($content, $status, $headers) creates response
session()Returns SessionInterfacesession('key') gets value, session(['key' => 'val']) sets value
validator()Returns ValidatorFactoryInterfacevalidator($data, $rules) creates validator

Sources: src/helpers/src/Functions.php111-660

Enum Value Extraction

The enum_value() function provides unified handling of PHP 8.1+ enums, extracting scalar values from both backed and unit enums. This utility is used throughout the codebase for enum normalization in requests, database operations, and API responses.


Sources: src/helpers/src/Functions.php244-267 tests/Helpers/HelpersTest.php134-152

Request Type Casting Methods

Request macros include specialized type casting methods that safely convert string input values to typed PHP values. The date() method supports Carbon instances, enum() validates and converts to enum cases, and primitive casters handle null defaults.

Type Casting Method Signatures


Sources: src/macros/src/RequestMixin.php58-106 src/macros/src/RequestMixin.php225-228 src/macros/src/RequestMixin.php145-148

Request Data Manipulation

The merge() and mergeIfMissing() methods modify request input data by updating the coroutine context. This pattern ensures data changes are isolated to the current coroutine while remaining accessible throughout the request lifecycle.


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

Testing Support

The helpers and macros include testing utilities for creating fake requests and validating behavior. The Request::fake() method creates PSR-7 compliant server request instances that can be configured via closures.

Test Helper Usage Patterns

PatternImplementationPurpose
Fake RequestRequest::fake()Create ServerRequest for testing
Configured FakeRequest::fake(fn($r) => $r->withMethod('POST'))Pre-configure request properties
Context InjectionContext::set(ServerRequestInterface::class, $fake)Inject fake into coroutine context
Mixin Registration(new RegisterMixinListener())->process($bootApplication)Register macros in test setup

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

Integration with Dependency Injection

The helper functions integrate seamlessly with Hyperf's coroutine-aware dependency injection system. The di() function serves as the foundation, checking for container availability and supporting both singleton retrieval and parameterized instantiation.


Sources: src/helpers/src/Functions.php169-191 src/helpers/src/Functions.php111-130 src/helpers/src/Functions.php344-361

Summary

The core utilities layer provides two complementary systems: global helper functions for framework resource access and data manipulation, and request macros that extend the HTTP request interface with Laravel-style convenience methods. These utilities are registered via ConfigProvider and boot listeners, integrate with Hyperf's coroutine context for isolation, and support comprehensive testing through fake request creation. The combination enables concise, expressive code while maintaining type safety through generic annotations and return type declarations.