PHP Luminova: Redis Cache
Store reusable values in Redis with named cache namespaces, expiration, and optional persistent connections.
Use RedisCache when application processes need to reuse cached values through a Redis server. Install the PHP Redis extension and configure the Redis endpoint before connecting.
Class Definition
- Full namespace:
Luminova\Cache\RedisCache - This class extends
Luminova\Base\AbstractCacheand inherits LazyObjectInterface. - This class is final.
Configuration
| Environment variable | Default | Description |
|---|---|---|
redis.host | 127.0.0.1 | Redis host. |
redis.port | 6379 | Redis port. |
redis.database | 0 | Redis database index. |
redis.password | null | Optional Redis password. |
redis.timeout | 0.0 | Connection timeout supplied to the Redis extension. |
redis.key.prefix | null | Optional Redis key prefix. |
redis.persistent.id | null | Persistent connection ID. If unset, the constructor checks system.cache.persistent.id. |
Usage
use Luminova\Cache\RedisCache;
$cache = new RedisCache(storage: 'products');
if ($cache->connect()) {
$cache->expiresAfter(300)->set('featured', ['sku-123']);
$featured = $cache->getItem('featured');
}Specify a storage name before accessing cache items. You can reuse the cache API described in File Cache for expiration, item lookup, and deletion.
Batch Reads and Invalidation
Reuse the connected $cache from the setup above. Use setItems() to store values with a shared lifetime, getItems() to read several keys, and deleteItems() to invalidate keys affected by an update.
if ($cache->isConnected()) {
$cache->setItems([
'stock:sku-123' => ['quantity' => 5],
'stock:sku-456' => ['quantity' => 12],
], expireAfter: 120);
$stock = $cache->getItems(['stock:sku-123', 'stock:sku-456']);
// After stock changes, invalidate the affected entry.
$cache->deleteItems(['stock:sku-123']);
}Methods
__construct
Configure the cache storage and persistent connection ID.
public function __construct(?string $storage = null, ?string $persistentId = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | Cache namespace (default null). |
$persistentId | string|null | Override the environment’s persistent connection ID (default null). |
connect
Open a Redis connection using the configured endpoint and select the configured database.
public function connect(): boolReturn:
bool - Whether the connection is available.
ping
Check for a response from the Redis server.
public function ping(): ?stringReturn:
string|null - The ping response or null when no response is available.
scan
Visit keys matching a pattern in the current cache storage.
public function scan(string $pattern, callable $onEachKey): intParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | Key pattern. |
$onEachKey | callable(string):mixed | Callback invoked for each matching key. |
Return:
int - Returns the number of keys processed.
getKeys
Collect keys matching a pattern in the current cache storage.
public function getKeys(?string $pattern = null): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string\|null | Key pattern. Null matches all keys in the current storage. |
Return:
string[] - Returns matching user keys, or an empty list when unavailable.
exists
Count the supplied keys that are present in the current storage.
public function exists(string|array $keys): intParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string\|string[] | A cache key or a list of keys to check. |
Return:
int - Returns the count reported by the cache backend, or zero when the storage or connection is unavailable.
setItems
Store several cache entries with a common expiration and lock setting. Empty keys and falsy values are skipped by this batch method. Use setItem() when storing a falsy value.
public function setItems(
array $items,
DateTimeInterface|int|null $expiration = 0,
DateInterval|int|null $expireAfter = null,
bool $lock = false
): intParameters:
| Parameter | Type | Description |
|---|---|---|
$items | array<string,mixed> | Cache values keyed by name. |
$expiration | DateTimeInterface\|int\|null | Expiration setting. Null uses the configured default. |
$expireAfter | DateInterval\|int\|null | Relative lifetime. When supplied or configured, it takes precedence over expiration. |
$lock | bool | Whether to lock the written entries. |
Return:
int - Returns the number reported as committed by the backend.
getInstance
Create the shared Redis cache instance on first use. Later calls reuse it.
public static function getInstance(
?string $storage = null,
?string $persistentId = null
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string\|null | Initial storage name. |
$persistentId | string\|null | Initial persistent connection identifier. |
Return:
self - Returns the shared cache instance.
getConn
Look up the client registered under this cache’s persistent connection identifier.
public function getConn(): ?RedisReturn:
Redis|null - Returns the registered Redis client or null.
disconnect
Close the current Redis client and clear its local connection state.
public function disconnect(): boolReturn:
bool - Returns true after resetting the cache connection state.
clear
Remove all keys scoped to the current cache storage.
public function clear(): boolReturn:
bool - Returns true when the storage was cleared.
flush
Flush the entire Redis database selected by the connection, including keys outside the current cache storage.
public function flush(): boolReturn:
bool - Returns true when Redis confirms the flush.
getDelayed
Prepare a batch lookup. With a callback, Redis reads matching keys immediately and delivers items to the callback. Otherwise read the prepared results with fetchNext() or fetchResult(). A new call resets the previous batch.
public function getDelayed(
array $keys,
bool $withCas = false,
?callable $onItem = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | Keys in the current storage. |
$withCas | bool | Accepted for compatibility. Redis does not supply CAS tokens. |
$onItem | callable(RedisCache,array{key:string,value:mixed}):void\|null | Optional item callback. |
Return:
bool - Returns true when a batch is prepared or matching values were processed by the callback.
fetchNext
Read the next key from a prepared batch and advance the cursor.
public function fetchNext(): ?arrayReturn:
array{key:string,value:mixed}|null - Returns the item, or null when the current key has no value or the batch is exhausted.
fetchResult
Read the prepared batch in one Redis multi-get and reset the batch state.
public function fetchResult(): arrayReturn:
array<int,array{key:string,value:mixed}> - Returns the batch items, or an empty array when there is no active batch.
getItem
Read one cache key. On a miss, metadata mode returns an empty item record with null data.
public function getItem(string $key, bool $withMetadata = false): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
$withMetadata | bool | Include cache metadata with each returned value. |
Return:
mixed - Returns the stored value, a metadata record, or null when no value is available and metadata was not requested.
getItems
Read and decode multiple Redis keys from the current storage.
public function getItems(array $keys, bool $withMetadata = false): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | Keys in the current storage. |
$withMetadata | bool | Include cache metadata with each returned value. |
Return:
array<string,mixed> - Returns the decoded results keyed by cache key.
setItem
Write one item in the current cache storage.
public function setItem(
string $key,
mixed $content,
DateTimeInterface|int|null $expiration = 0,
DateInterval|int|null $expireAfter = null,
bool $lock = false
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
$content | mixed | Value to store. |
$expiration | DateTimeInterface\|int\|null | Expiration or null to use the configured setting. |
$expireAfter | DateInterval\|int\|null | Relative expiration or null to use the configured setting. |
$lock | bool | Lock the item against ordinary deletion. |
Return:
bool - Returns the result of the write.
hasItem
Check whether a key exists in loaded cache data or Redis.
public function hasItem(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
Return:
bool - Returns true when the key is found.
isLocked
Check the lock flag on an entry that can be loaded.
public function isLocked(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
Return:
bool - Returns true when the stored lock flag is set.
hasExpired
Check whether a key is missing, unreadable, or past its expiration.
public function hasExpired(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
Return:
bool - Returns true if the key cannot be loaded or the entry has expired.
deleteItem
Delete one item in the current storage.
public function deleteItem(string $key, bool $gcExpiredLocks = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | Cache key in the current storage. |
$gcExpiredLocks | bool | Bypass the lock check when true. |
Return:
bool - Returns true when the entry is already absent or Redis deletes it.
deleteItems
Apply deleteItem() to multiple keys. Skips empty strings.
public function deleteItems(iterable $keys, bool $gcExpiredLocks = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | iterable<string> | Keys to delete. |
$gcExpiredLocks | bool | Bypass the lock check when true. |
Return:
bool - Returns true when at least one key yields a successful result.
delete
Delete specified Redis keys from the current storage or a named storage without changing the active namespace.
public function delete(array $keys, ?string $storage = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | Keys in the current storage. |
$storage | string\|null | Optional storage name. Null uses the current storage. |
Return:
bool - Returns true if Redis deletes at least one key.