VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/3.1-global-helper-functions

⇱ Global Helper Functions | friendsofhyperf/components | DeepWiki


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

Global Helper Functions

The helpers component provides 50+ global convenience functions that offer Laravel-style shortcuts for common operations in Hyperf applications. These functions provide direct access to container services, request/response handling, data transformation, caching, logging, and validation without requiring explicit dependency injection.

For information about request macro methods (like validate(), collect(), date()), see Request Macros and Extensions. For the unified job dispatch API, see Fluent Dispatch API and Job Routing. For fluent data structures and transformation utilities, see Data Transformation Utilities.

Architecture and Container Integration

The helper functions serve as a thin convenience layer over Hyperf's dependency injection container and core services. Most functions internally call di() or ApplicationContext::getContainer() to resolve services.


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

Function Categories


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

Container and Dependency Injection

di()

Returns the container instance or resolves a service from the container. This is the foundational function that most other helpers use internally.

Signature:


Behavior:

  • Without arguments: Returns ContainerInterface
  • With class name and no parameters: Calls $container->get($abstract) if the binding exists
  • With parameters: Calls $container->make($abstract, $parameters) to construct with dependencies

Example Usage:


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

app()

Provides a Laravel-style alias to di() with support for callable wrapping.

Signature:


Special Behavior:

  • If $abstract is callable, wraps it in a Closure::fromCallable()
  • Otherwise delegates to di()

Example Usage:


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

resolve()

Another alias to di() for service resolution, primarily for Laravel compatibility.

Signature:


Sources: src/helpers/src/Functions.php447-454

HTTP Request and Response

request()

Retrieves the current HTTP request or extracts input values from it.

Signature:


Return Types:

  • No arguments: Returns RequestInterface
  • String key: Returns input value for that key
  • Array of keys: Returns array of values for those keys

Example Usage:


Sources: src/helpers/src/Functions.php462-475

response()

Creates a new HTTP response with optional content, status, and headers.

Signature:


Special Behavior:

  • No arguments: Returns ResponseInterface instance
  • Array content: Automatically sets Content-Type: application/json and encodes
  • String content: Sets as body with SwooleStream

Example Usage:


Sources: src/helpers/src/Functions.php484-507

cookie()

Creates cookie instances or retrieves the cookie jar.

Signature:


Parameters:

  • $name: Cookie name (null returns CookieJarInterface)
  • $value: Cookie value
  • $minutes: Expiration in minutes (0 = session cookie)
  • $path, $domain, $secure, $httpOnly, $raw, $sameSite: Standard cookie attributes

Sources: src/helpers/src/Functions.php137-146

get_client_ip()

Extracts the client IP address from headers or server variables.

Logic:

  1. Checks X-Real-IP header first
  2. Falls back to REMOTE_ADDR server variable

Example Usage:


Sources: src/helpers/src/Functions.php306-311

Cache and Session

cache()

Multi-purpose cache accessor that can retrieve the cache instance, get values, or set values.

Signature:


Usage Patterns:

PatternBehavior
cache()Returns CacheInterface instance
cache('key')Gets value for 'key'
cache('key', 'default')Gets with default value
cache(['key' => 'value'])Sets key-value pair
cache(['key' => 'value'], 3600)Sets with TTL in seconds

Example Usage:


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

session()

Multi-purpose session accessor for getting/setting session values.

Signature:


Behavior:

  • No arguments: Returns SessionInterface
  • String key: Gets value from session
  • Array: Puts all key-value pairs into session (returns void)

Example Usage:


Sources: src/helpers/src/Functions.php542-556

Data Transformation and Validation

transform()

Applies a transformation callback to a value only if the value is "filled" (not blank).

Signature:


Logic Flow:


Example Usage:


Sources: src/helpers/src/Functions.php634-645 tests/Helpers/HelpersTest.php112-132

rescue()

Catches exceptions and returns a default value, with optional exception handling callback.

Signature:


Parameters:

  • $callback: Function to execute (may throw)
  • $rescue: Default value or callable that receives the exception
  • $exceptionHandler: Optional callback for side effects (logging, etc.)

Example Usage:


Sources: src/helpers/src/Functions.php520-531 tests/Helpers/HelpersTest.php154-191

enum_value()

Extracts the scalar value from an enum or returns the value unchanged.

Signature:


Behavior:

  • BackedEnum: Returns $value->value
  • UnitEnum: Returns $value->name
  • Empty string: Returns empty string
  • Other types: Returns value unchanged

Example Usage:


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

blank() and filled()

Determine if a value is blank (empty) or filled (non-empty).

blank() Logic:


Key Points:

  • Numeric and boolean values are never blank (even 0, 0.0, false)
  • Model instances are never blank
  • Whitespace-only strings are blank
  • Stringable objects are checked after trimming

Example Usage:


Sources: src/helpers/src/Functions.php90-101 src/helpers/src/Functions.php288-291 tests/Helpers/HelpersTest.php73-104

fluent()

Creates a Fluent object for dynamic property access to arrays/objects.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php298-301

literal()

Creates an anonymous object using named arguments.

Signature:


Behavior:

  • Single list argument: Returns that argument unchanged
  • Named arguments: Creates stdClass with properties

Example Usage:


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

object_get()

Retrieves values from objects using dot notation.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php409-424 tests/Helpers/HelpersTest.php31-37

preg_replace_array()

Replaces pattern matches sequentially with values from an array.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php429-436 tests/Helpers/HelpersTest.php39-62

Validation

validator()

Creates a validator instance or returns the validator factory.

Signature:


Usage Patterns:

CallReturns
validator()ValidatorFactoryInterface
validator($data, $rules)ValidatorInterface instance

Example Usage:


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

Logging and Debugging

logger() and logs()

Provide access to logging functionality.

logger() Signature:


logs() Signature:


Behavior:

  • logger() without arguments: Returns default logger
  • logger($message): Logs at DEBUG level
  • logger($message, $context, true): Includes backtrace in context
  • logs($name, $group): Returns specific named logger

Example Usage:


Sources: src/helpers/src/Functions.php344-361

info()

Convenience function for info-level logging.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php316-324

Control Flow

throw_if() and throw_unless()

Conditionally throw exceptions based on a condition.

Signatures:


Exception Handling:

  1. If $exception is a class name: Instantiates with $parameters
  2. If $exception is a string: Wraps in RuntimeException
  3. If $exception is an instance: Throws directly

Return Value: Returns $condition if no exception thrown (for chaining)

Example Usage:


Sources: src/helpers/src/Functions.php583-620

when()

Conditionally returns a value based on an expression.

Signature:


Logic:

  1. Evaluates $expr (calls if callable)
  2. If truthy: Returns $value
  3. If falsy: Returns $default
  4. If result is Closure: Calls with $expr as argument

Example Usage:


Sources: src/helpers/src/Functions.php676-681

Date and Time Helpers

The helpers component provides convenience functions for creating CarbonInterval instances. These functions return interval objects that can be used with Carbon or passed to cache TTLs.

Available Functions:

FunctionCreates
microseconds(int $microseconds)Microsecond interval
milliseconds(int $milliseconds)Millisecond interval
months(int $months)Month interval
weeks(int $weeks)Week interval

Example Usage:


Sources: src/helpers/src/Functions.php366-385 src/helpers/src/Functions.php665-668

Event Dispatching

event()

Dispatches an event through the event dispatcher and returns the event object.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php278-281

Utility Functions

base_path()

Returns the base path of the application with an optional relative path appended.

Signature:


Implementation: Uses the BASE_PATH constant and joins paths with /.

Example Usage:


Sources: src/helpers/src/Functions.php80-83

class_namespace()

Extracts the namespace from a class name or object.

Signature:


Example Usage:


Sources: src/helpers/src/Functions.php153-158 tests/Helpers/HelpersTest.php26-29

Deprecated Functions

The following functions are deprecated and will be removed in version 3.2:

dispatch()

Status: Deprecated in v3.1, removed in v3.2
Replacement: Use FriendsOfHyperf\Support\dispatch() instead

The helper version had routing logic for AsyncQueue, AMQP, Kafka, and AsyncTask but is being moved to the Support component for better organization.

Sources: src/helpers/src/Functions.php194-225

environment()

Status: Deprecated in v3.1, removed in v3.2
Replacement: Use Str::is($patterns, env('APP_ENV')) instead

Previously provided environment checking functionality but is superseded by direct pattern matching.

Sources: src/helpers/src/Functions.php232-241

now() and today()

Status: Deprecated in v3.1, removed in v3.2
Replacement: Use Hyperf\Support\now() and Hyperf\Support\today() instead

These Carbon date creation functions have been moved to Hyperf's core Support component.

Sources: src/helpers/src/Functions.php394-397 src/helpers/src/Functions.php565-568

Helper Function Resolution Flow


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

Testing Patterns

Helper functions are designed to be testable through container mocking. The test suite demonstrates common patterns:

Mock Container Services:


Test Helper Behavior:


Sources: tests/Helpers/HelpersTest.php1-209 tests/TestCase.php27-41