VOOZH about

URL: https://deepwiki.com/hypervel/components/6.1-cache-manager-and-drivers

⇱ Cache Manager and Drivers | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

Cache Manager and Drivers

Purpose and Scope

This document covers the cache manager factory pattern and the built-in cache drivers available in Hypervel. The CacheManager class serves as the central factory for creating and managing cache store instances, each wrapped in a Repository for a consistent API. Multiple driver implementations are provided, including Redis, File, Array, Database, Swoole, Stack, and Null stores.

For information about the Swoole Store's memory management and eviction policies, see 6.2. For multi-tier caching with the Stack Store, see 6.3. For rate limiting and distributed locks built on the cache system, see 6.4.


Architecture Overview

The cache system follows a layered factory pattern where the CacheManager creates driver-specific store instances and wraps them in a Repository class that provides the unified cache API.

Cache System Architecture


Sources: src/cache/src/CacheManager.php1-335


CacheManager Factory

The CacheManager class implements the Hypervel\Cache\Contracts\Factory interface and serves as the central factory for all cache operations. It maintains a registry of resolved store instances and supports dynamic driver creation.

Core Factory Methods

MethodPurposeReturn Type
store(?string $name = null)Get a cache store instance by nameRepositoryContract
driver(?string $driver = null)Alias for store()RepositoryContract
repository(Store $store, array $config = [])Create a new Repository wrapperRepository
extend(string $driver, Closure $callback)Register a custom driver creatorstatic
getDefaultDriver()Get the default cache driver name from configstring
setDefaultDriver(string $name)Set the default cache driver namevoid
forgetDriver(array|string|null $name = null)Remove resolved driver instances from memorystatic
purge(?string $name = null)Disconnect and remove a drivervoid

Store Resolution and Caching


Sources: src/cache/src/CacheManager.php56-191

Magic Method Delegation

The CacheManager implements __call() to delegate method calls to the default driver's repository:


This allows calling cache methods directly on the manager: $cacheManager->get('key') automatically delegates to $cacheManager->store()->get('key').

Sources: src/cache/src/CacheManager.php48-51


Driver Resolution Strategy

The CacheManager uses a multi-step resolution process to instantiate cache drivers:

Driver Resolution Flow


Sources: src/cache/src/CacheManager.php172-191

Configuration Structure

Each cache store is configured in config/cache.php under the stores key:


The driver key determines which creation method is called. The events key controls whether cache events are dispatched.

Sources: src/cache/src/CacheManager.php327-334


Built-in Drivers

The CacheManager provides factory methods for seven built-in cache drivers, each optimized for different use cases.

Array Store

The ArrayStore provides an in-memory cache using a PHP array. This is primarily useful for testing or for caching data within a single request.

Creation Method: src/cache/src/CacheManager.php204-207


Configuration Options:

OptionTypeDefaultDescription
serializeboolfalseWhether to serialize values before storing

The serialize option enables serialization for testing behavior that matches persistent stores.

Sources: src/cache/src/CacheManager.php204-207

File Store

The FileStore persists cache entries as individual files on disk. Each cache key corresponds to a file containing the serialized value and expiration timestamp.

Creation Method: src/cache/src/CacheManager.php212-220


Configuration Options:

OptionTypeDescription
pathstringDirectory path for cache files
permissionint|nullFile permissions (e.g., 0755)
lock_pathstring|nullDirectory for lock files

The lock directory is used for distributed locking (see 6.4).

Sources: src/cache/src/CacheManager.php212-220

Redis Store

The RedisStore uses Redis for high-performance distributed caching with support for multiple connection pools and distributed locking.

Creation Method: src/cache/src/CacheManager.php233-245


Configuration Options:

OptionTypeDefaultDescription
connectionstring'default'Redis connection name from Hyperf config
lock_connectionstringSame as connectionSeparate connection for locks
prefixstringConfig defaultKey prefix for all cache entries

The RedisStore integrates with Hyperf's RedisFactory to leverage connection pooling and coroutine safety.

Sources: src/cache/src/CacheManager.php233-245

Database Store

The DatabaseStore stores cache entries in a database table, providing persistent storage with query-based operations.

Creation Method: src/cache/src/CacheManager.php285-300


Configuration Options:

OptionTypeDefaultDescription
connectionstring'default'Database connection name
tablestringRequiredTable name for cache entries
lock_tablestring'cache_locks'Table for distributed locks
lock_lotteryarray[2, 100]Probability [hits, total] for lock cleanup
lock_timeoutint86400Lock timeout in seconds

The database driver requires migration to create the cache tables.

Sources: src/cache/src/CacheManager.php285-300

Swoole Store

The SwooleStore uses Swoole Table for ultra-fast shared memory caching across coroutines with advanced eviction policies. See 6.2 for detailed coverage.

Creation Method: src/cache/src/CacheManager.php250-261


Configuration Options:

OptionTypeDefaultDescription
tablestringRequiredSwoole table name from cache.swoole_tables
memory_limit_bufferfloat0.05Memory buffer threshold (5%)
eviction_policystring'lru'Eviction policy: 'lru', 'lfu', 'ttl', 'noeviction'
eviction_proportionfloat0.05Proportion of entries to evict (5%)

The SwooleTableManager is responsible for creating and configuring the underlying Swoole Table structures.

Sources: src/cache/src/CacheManager.php250-261 src/cache/src/SwooleTableManager.php1-63

Stack Store

The StackStore implements multi-tier hierarchical caching, allowing multiple cache stores to be stacked with automatic backfilling. See 6.3 for detailed coverage.

Creation Method: src/cache/src/CacheManager.php266-280


Configuration Structure:


Each store in the stack can have an optional ttl limit enforced by StackStoreProxy.

Sources: src/cache/src/CacheManager.php266-280

Null Store

The NullStore is a no-op implementation that doesn't store anything. It's useful for disabling caching in certain environments.

Creation Method: src/cache/src/CacheManager.php225-228


No configuration options are needed. This driver always returns null for reads and true for writes.

Sources: src/cache/src/CacheManager.php225-228 src/cache/src/CacheManager.php329-333


SwooleTableManager

The SwooleTableManager is a specialized factory for creating and managing Swoole Table instances used by the SwooleStore.

SwooleTableManager Structure


Table Creation: src/cache/src/SwooleTableManager.php21-33


Table Schema:

ColumnTypeSizePurpose
valueSTRINGConfigurableSerialized cache value
expirationFLOAT8 bytesUnix timestamp with microseconds
last_used_atFLOAT8 bytesLast access time for LRU eviction
used_countINT8 bytesAccess count for LFU eviction

Configuration Options:

OptionTypeDefaultDescription
rowsint1024Maximum number of cache entries
bytesint10240Maximum size of each value (10KB)
conflict_proportionfloat0.2Hash collision proportion (20%)

The SwooleTable class extends Swoole's native Table to add validation that prevents storing values larger than the configured byte size.

Sources: src/cache/src/SwooleTableManager.php1-63 src/cache/src/SwooleTable.php1-64


Repository Wrapper

While the Repository class implementation is not shown in the provided files, its role in the architecture is critical. The CacheManager always wraps concrete Store implementations in a Repository instance before returning them to clients.

Repository Creation and Configuration


Repository Creation: src/cache/src/CacheManager.php74-81


The Repository provides:

  1. Unified API: A consistent interface regardless of underlying store
  2. Event Integration: Optional event dispatching for cache operations
  3. Additional Methods: Helper methods like remember(), rememberForever(), etc.
  4. Lock Provider: Access to distributed locking capabilities

Sources: src/cache/src/CacheManager.php74-81


Event Integration

Cache repositories can optionally dispatch events for cache operations when configured with 'events' => true.

Event Dispatcher Configuration


Event Dispatcher Injection: src/cache/src/CacheManager.php305-314


Refreshing Event Dispatchers

When the event dispatcher instance changes, all existing repositories can be updated:

src/cache/src/CacheManager.php86-93


This method is typically called by service providers when the event dispatcher is reconfigured.

Sources: src/cache/src/CacheManager.php86-93 src/cache/src/CacheManager.php305-314


Custom Drivers

The CacheManager supports registering custom cache drivers through the extend() method, allowing developers to implement specialized caching backends.

Custom Driver Registration Flow


Registration Example:


Custom Creator Implementation: src/cache/src/CacheManager.php142-147


The closure is bound to the CacheManager instance, giving it access to protected methods like repository() and getPrefix().

Custom Creator Invocation: src/cache/src/CacheManager.php196-199


Custom creators receive:

  1. The application container instance
  2. The full configuration array for the store

They must return a RepositoryContract instance, typically by calling $this->repository().

Sources: src/cache/src/CacheManager.php142-147 src/cache/src/CacheManager.php196-199 src/cache/src/CacheManager.php180-182


Global Cache Helper

The cache system provides a global cache() helper function for convenient access to the cache manager.

Helper Function Behavior:


Implementation: src/cache/src/Functions.php21-40


The function delegates to the CacheManager's magic __call() method, which forwards to the default store's repository.

Sources: src/cache/src/Functions.php1-40