VOOZH about

URL: https://deepwiki.com/hypervel/cache/5.4-helper-functions

⇱ Helper Functions | hypervel/cache | DeepWiki


Loading...
Menu

Helper Functions

This document covers the global helper function provided by the hypervel/cache package for simplified cache access. The cache() helper provides a convenient, polymorphic API for interacting with the cache system without requiring explicit dependency injection. For information about the underlying CacheManager factory, see 2.1. For details about the Repository interface used by the helper, see 2.2.

Purpose and Scope

The cache() helper function provides a polymorphic API with three operational modes determined by parameter types: factory access (null), cache retrieval (string key), and cache storage (array). The function leverages PHPDoc conditional return types for static analysis support.


The cache() Helper Function

The cache() function serves as a polymorphic gateway to the cache system, changing its behavior based on the arguments provided.

Function Signature

The function is defined in src/Functions.php21-40 with the following signature:


The function accepts two parameters:

  • $key: Can be null, a string (cache key), or an array (key-value pairs for storage)
  • $default: Can be a default value (for retrieval), TTL in seconds (for storage), or null

Sources: src/Functions.php21-22

Behavioral Modes

Diagram: cache() Function Control Flow with Method Calls


Sources: src/Functions.php25-40

Type-Based Dispatch Table

ConditionCode CheckMethod CallReturn Type
No argumentsis_null($key)Return $managerCacheManager
String keyis_string($key)$manager->get($key, $default)mixed
Array datais_array($key)$manager->put(key($key), reset($key), $default)bool
Invalid type!is_array($key)Throw InvalidArgumentExceptionNever returns

Sources: src/Functions.php25-40

<old_str>

ApplicationContext Integration

src/Functions.php23 retrieves the CacheManager singleton from Hyperf's container:


This design ensures the helper accesses the same configured CacheManager instance used by dependency-injected components, maintaining consistency across the application.

Sources: src/Functions.php7-23 </old_str> <new_str>

Container Resolution and Method Dispatch

Diagram: cache() Function Execution Flow with Actual Methods


Sources: src/Functions.php21-40 </old_str>

<old_str>

ApplicationContext Usage

src/Functions.php23 retrieves the container using Hyperf's ApplicationContext:


This approach ensures the helper function:

  • Uses the same configured CacheManager instance throughout the application
  • Benefits from container caching and singletons
  • Maintains consistency with other dependency-injected components

Sources: src/Functions.php7-23

<old_str>

ApplicationContext Usage

src/Functions.php23 retrieves the container using Hyperf's ApplicationContext:


This approach ensures the helper function:

  • Uses the same configured CacheManager instance throughout the application
  • Benefits from container caching and singletons
  • Maintains consistency with other dependency-injected components

Sources: src/Functions.php7-23


Mode 1: Factory Access

When called without arguments, cache() returns the CacheManager instance, allowing direct access to the factory for advanced operations.

Implementation

src/Functions.php23-26 retrieves the CacheManager from the application container and returns it directly when $key is null:


Usage Examples

CodeDescriptionReturn Type
cache()Get the CacheManager instanceCacheManager
cache()->store('redis')Get a specific storeRepository
cache()->driver('file')Alias for getting a storeRepository
cache()->getDefaultDriver()Get default driver namestring

This mode enables access to all CacheManager methods documented in 2.1, including store selection, custom driver registration, and configuration management.

Sources: src/Functions.php23-26


Mode 2: Cache Retrieval

When called with a string key, cache() retrieves a value from the default cache store.

Implementation

src/Functions.php29-30 performs a GET operation on the default store:


The CacheManager::get() method delegates to the default store's Repository, which is covered in 2.2.

Usage Examples

CodeDescriptionReturn Value
cache('user:123')Retrieve value, return null if missingmixed or null
cache('user:123', [])Retrieve value, return [] if missingmixed or []
cache('config', fn() => loadConfig())Retrieve or execute closure and cachemixed

Default Value Behavior

The $default parameter accepts:

  • Primitive values: Returned directly if key is missing
  • Closures: Executed and result is cached with the remember() pattern (see 2.2)
  • null: Standard behavior, returns null for cache misses

Sources: src/Functions.php29-30


Mode 3: Cache Storage

When called with an array as the first argument, cache() stores a key-value pair in the default cache store.

Implementation

src/Functions.php33-39 extracts the key and value from the array and performs a PUT operation:


The implementation uses:

  • key($key): Extracts the first key from the array
  • reset($key): Extracts the first value from the array
  • $default: Interpreted as TTL (time-to-live) in seconds

Usage Examples

CodeDescriptionTTL
cache(['user:123' => $user])Store indefinitely (forever)Forever
cache(['user:123' => $user], 3600)Store for 1 hour3600 seconds
cache(['token' => $jwt], 60)Store for 1 minute60 seconds
cache(['temp' => $data], null)Store indefinitelyForever

Return Value

The function returns bool indicating success or failure of the PUT operation.

Sources: src/Functions.php33-39


Error Handling

The helper function validates input types at runtime to ensure type safety beyond PHP's type system.

Invalid Argument Detection

src/Functions.php33-37 throws an InvalidArgumentException if the first argument is not null, a string, or an array:


This validation ensures that the polymorphic behavior is predictable and prevents silent failures from incorrect usage.

Sources: src/Functions.php8-37


Type Safety and PHPDoc Annotations

The function uses advanced PHPDoc annotations to provide IDE autocompletion and static analysis support.

Conditional Return Types

src/Functions.php17 declares conditional return types based on parameter types:


This annotation tells static analysis tools:

  • If $key is null, return type is CacheManager
  • If $key is a string, return type is mixed (retrieved value)
  • Otherwise (array), return type is bool (success indicator)

Parameter Documentation

src/Functions.php15-16 documents the dual purpose of parameters:


This notation indicates that parameter semantics change based on the operation mode.

Sources: src/Functions.php15-17


Integration with Framework

The helper function integrates with Hyperf's dependency injection container to access the cache system.

Container Resolution


Sources: src/Functions.php23

ApplicationContext Usage

src/Functions.php23 retrieves the container using Hyperf's ApplicationContext:


This approach ensures the helper function:

  • Uses the same configured CacheManager instance throughout the application
  • Benefits from container caching and singletons
  • Maintains consistency with other dependency-injected components

Sources: src/Functions.php7-23


Comparison with Direct Usage

The helper function provides a convenient alternative to direct dependency injection, with tradeoffs to consider.

Feature Comparison

AspectHelper FunctionDirect Injection
Syntaxcache('key')$cache->get('key')
DI ContainerImplicit accessExplicit dependency
TestabilityHarder to mockEasy to mock
Type SafetyPHPDoc-basedNative PHP types
Store SelectionVia factory modeConstructor parameter
Code LengthShorterMore verbose

When to Use Helper

The cache() helper is ideal for:

  • Simple cache operations in controllers, commands, and event listeners
  • Quick prototyping and development
  • One-off cache access without dedicated service classes
  • Global utility functions

When to Use Direct Injection

Direct CacheManager or Repository injection is preferred for:

  • Service classes with testability requirements
  • Complex cache operations requiring multiple store access
  • Performance-critical code (avoids container lookup overhead)
  • Strict type safety requirements

Sources: src/Console/ClearCommand.php58-62 (example of direct injection)


Examples in Console Commands

The ClearCommand demonstrates practical usage patterns for accessing the cache system.

Direct Injection Pattern in Console Commands

Diagram: ClearCommand Cache Access Pattern


src/Console/ClearCommand.php56-62 demonstrates explicit container resolution:


Method call sequence:

  1. $this->app->get(CacheContract::class) - Resolves CacheManager from container
  2. ->store($this->argument('store')) - Selects named store (defaults to configured driver)
  3. ->tags($this->tags()) - Optionally applies tag filtering for tagged operations

This explicit pattern provides better testability than the global cache() helper by allowing mock injection of CacheContract.

Sources: src/Console/ClearCommand.php56-62


Summary

The cache() helper function provides three operational modes accessed through a single polymorphic interface:

ModeCall PatternPurposeReturn Type
Factorycache()Access CacheManagerCacheManager
Retrievalcache(string, mixed)Get cached valuemixed
Storagecache(array, int)Put value with TTLbool

The helper simplifies common cache operations while maintaining access to the full power of the CacheManager factory and Repository facade patterns documented in sections 2.1 and 2.2.

Sources: src/Functions.php1-41