VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5.1-cache-component

⇱ Cache Component | friendsofhyperf/components | DeepWiki


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

Cache Component

The Cache Component provides an enhanced caching layer for Hyperf applications that extends the base hyperf/cache package with Laravel-style features. It offers atomic operations for race-condition-free updates, distributed lock integration for coordinated access, cache tagging for grouped invalidation, and event dispatching for observability. The component maintains API compatibility with Hyperf's native cache system while adding convenience methods and integration patterns.

For distributed locking mechanisms used by this component, see Lock Component. For helper functions that access the cache, see Global Helper Functions.

Purpose and Scope

This component wraps Hyperf's cache drivers (Redis, File, Memory, etc.) with additional functionality:

  • Atomic Operations: remember(), rememberForever(), pull() methods that prevent race conditions
  • Lock Integration: Optional integration with Lock Component for coordinated cache access
  • Event Dispatching: Lifecycle events for cache hits, misses, writes, and deletes
  • Macro Support: Runtime extension of cache functionality via Macroable trait
  • Deferred Operations: Integration with coroutines for asynchronous cache updates
  • Tag Support: Grouped cache key invalidation (driver-dependent)

The component does not replace Hyperf's cache drivers but augments them with higher-level abstractions.

Sources: src/cache/composer.json1-48

Component Architecture


Diagram: Cache Component Integration Architecture with Package Boundaries

The component acts as a facade layer over Hyperf's native cache system, adding conveniences while maintaining compatibility with underlying drivers.

Sources: src/cache/composer.json22-34

Configuration and Setup

Installation

Install via Composer:


The component automatically registers through Hyperf's ConfigProvider system and requires no additional setup for basic usage.

Dependencies

PackagePurposeVersion
hyperf/cacheBase cache system~3.1.0
hyperf/collectionData structures~3.1.0
hyperf/contextCoroutine context~3.1.0
hyperf/macroableRuntime extensions~3.1.0
nesbot/carbonDate/time handling^2.0 || ^3.0
friendsofhyperf/lockDistributed locking (optional)~3.1.0
hyperf/coroutineAsync operations (optional)~3.1.0

Sources: src/cache/composer.json22-34

ConfigProvider Registration

The component registers via FriendsOfHyperf\Cache\ConfigProvider which integrates with Hyperf's dependency injection container. Configuration files use Hyperf's standard config/autoload/cache.php format.

Sources: src/cache/composer.json44-46

Core Components and Code Structure

The cache component extends Hyperf\Cache\CacheManager with additional repository classes and event dispatching:


Diagram: Cache Component Class Hierarchy and Namespaces

Key Classes

ClassNamespacePurpose
ConfigProviderFriendsOfHyperf\CacheRegisters services with DI container
RepositoryFriendsOfHyperf\CacheMain cache operations implementation
CacheManagerFriendsOfHyperf\CacheFactory for cache drivers
CacheHitFriendsOfHyperf\Cache\EventEvent dispatched on cache hit
CacheMissedFriendsOfHyperf\Cache\EventEvent dispatched on cache miss
KeyWrittenFriendsOfHyperf\Cache\EventEvent dispatched on write
KeyForgottenFriendsOfHyperf\Cache\EventEvent dispatched on delete
CacheFlushedFriendsOfHyperf\Cache\EventEvent dispatched on flush

The Repository class implements Hyperf\Cache\CacheInterface and adds Macroable support via the Hyperf\Macroable\Macroable trait.

Sources: src/cache/composer.json22-28 src/cache/composer.json37-46

Atomic Operations

Atomic operations prevent race conditions when multiple processes access the same cache key:

remember() Method

Retrieves a value from cache or computes and stores it atomically:


Behavior:

  1. Check cache for key
  2. If exists, dispatch CacheHit event and return value
  3. If missing, acquire lock (if lock component available)
  4. Execute closure to compute value
  5. Store result with TTL
  6. Dispatch KeyWritten event
  7. Return value

rememberForever() Method

Similar to remember() but stores indefinitely:


pull() Method

Retrieves and deletes a key atomically:


Sources: src/cache/composer.json22-34

Lock Integration

When friendsofhyperf/lock is installed, the cache component provides lock acquisition for coordinated access patterns:


Diagram: Cache Lock Integration Flow

lock() Method

Explicitly acquire a lock for manual coordination:


Sources: src/cache/composer.json31-33 src/lock/composer.json1-54

Event System

The cache component dispatches lifecycle events for observability and integration with monitoring systems:

Event ClassTriggerPropertiesWhen Dispatched
CacheHitKey found in cachekey, value, tagsAfter successful get()
CacheMissedKey not foundkey, tagsAfter failed get()
KeyWrittenValue storedkey, value, seconds, tagsAfter successful put()
KeyForgottenKey deletedkey, tagsAfter forget() operation
CacheFlushedCache clearedtagsAfter flush() operation

Event Dispatching Behavior


Diagram: Cache Event Dispatch Flow

Event Listener Example


Event Failure Handling

The KeyForgotten event is dispatched even when forget() returns false, allowing listeners to track failed deletion attempts. This behavior was fixed in version 3.1.63 to ensure consistent event dispatching.

These events integrate with Sentry tracing for breadcrumb generation and Telescope debugging for request lifecycle observation.

Sources: CHANGELOG-3.1.md250-252 CHANGELOG-3.1.md306 src/cache/composer.json22-28

Cache Tagging

Tags enable grouped invalidation of related cache keys:


Tag Limitations:

DriverTag Support
Redis✅ Supported
Memcached✅ Supported
File❌ Not supported
Memory❌ Not supported
Database❌ Not supported

Attempting to use tags with unsupported drivers will throw an exception.

Sources: src/cache/composer.json23

Deferred Operations

When hyperf/coroutine is available, the component supports deferred cache writes:


This pattern reduces response latency for non-critical cache updates.

Sources: src/cache/composer.json33

Macroable Extensions

The Repository class uses Hyperf\Macroable\Macroable trait, enabling runtime method additions without modifying the component source code:

Defining Macros


Using Macros


Integration with Macros Component

Macros can also be defined via the macros component which provides additional macro registration patterns for common Hyperf classes including cache repositories.

Sources: src/cache/composer.json26 src/macros/composer.json1-56

Integration with Other Components

With Lock Component


Diagram: Cache and Lock Integration

The cache component optionally uses locks for atomic operations, preventing the "thundering herd" problem during cache misses.

Sources: src/cache/composer.json31-32

With Helper Functions

The global cache() helper from friendsofhyperf/helpers provides convenient access:


Sources: src/helpers/composer.json1-64

With Facade System

The Cache facade from friendsofhyperf/facade enables static access:


Sources: src/facade/composer.json31

Driver Compatibility Matrix

FeatureRedisFileMemoryDatabaseMemcached
Basic get/put
TTL support
Atomic operations⚠️⚠️⚠️
Lock integration
Cache tags
Event dispatching
Deferred writes

⚠️ = Limited support due to process isolation

Recommended Production Setup: Redis driver with Lock component for full feature support.

Sources: src/cache/composer.json22-34

Usage Patterns

Pattern 1: Query Result Caching


Pattern 2: Rate Limiting with Pull


Pattern 3: Invalidation by Tag


Pattern 4: Coordinated Updates


Sources: src/cache/composer.json1-48

Comparison with Base Hyperf Cache

FeatureHyperf CacheFriendsOfHyperf Cache
Driver system✅ Core implementation✅ Uses Hyperf drivers
Basic operations✅ get/put/delete✅ All basic operations
Atomic remember()❌ Not built-in✅ Race-condition safe
Lock integration❌ Manual implementation✅ Automatic coordination
Event dispatching❌ Not available✅ Full lifecycle events
Macroable❌ Not extensible✅ Runtime extensions
Laravel compatibility❌ Different API✅ Laravel-style methods
Tag support✅ Via DriverInterface✅ Enhanced tag API

The component provides a Laravel-familiar API while maintaining full compatibility with Hyperf's cache infrastructure.

Sources: src/cache/composer.json1-48