Luminova Framework

PHP Luminova: Redis Cache

Last updated: 2026-11-28 20:57:12

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\AbstractCache and inherits LazyObjectInterface.
  • This class is final.

Configuration

Environment variableDefaultDescription
redis.host127.0.0.1Redis host.
redis.port6379Redis port.
redis.database0Redis database index.
redis.passwordnullOptional Redis password.
redis.timeout0.0Connection timeout supplied to the Redis extension.
redis.key.prefixnullOptional Redis key prefix.
redis.persistent.idnullPersistent 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:

ParameterTypeDescription
$storagestring|nullCache namespace (default null).
$persistentIdstring|nullOverride 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(): bool

Return:

bool - Whether the connection is available.


ping

Check for a response from the Redis server.

public function ping(): ?string

Return:

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): int

Parameters:

ParameterTypeDescription
$patternstringKey pattern.
$onEachKeycallable(string):mixedCallback 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): array

Parameters:

ParameterTypeDescription
$patternstring\|nullKey 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): int

Parameters:

ParameterTypeDescription
$keysstring\|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
): int

Parameters:

ParameterTypeDescription
$itemsarray<string,mixed>Cache values keyed by name.
$expirationDateTimeInterface\|int\|nullExpiration setting. Null uses the configured default.
$expireAfterDateInterval\|int\|nullRelative lifetime. When supplied or configured, it takes precedence over expiration.
$lockboolWhether 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
): self

Parameters:

ParameterTypeDescription
$storagestring\|nullInitial storage name.
$persistentIdstring\|nullInitial 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(): ?Redis

Return:

Redis|null - Returns the registered Redis client or null.


disconnect

Close the current Redis client and clear its local connection state.

public function disconnect(): bool

Return:

bool - Returns true after resetting the cache connection state.


clear

Remove all keys scoped to the current cache storage.

public function clear(): bool

Return:

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(): bool

Return:

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
): bool

Parameters:

ParameterTypeDescription
$keysstring[]Keys in the current storage.
$withCasboolAccepted for compatibility. Redis does not supply CAS tokens.
$onItemcallable(RedisCache,array{key:string,value:mixed}):void\|nullOptional 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(): ?array

Return:

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(): array

Return:

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): mixed

Parameters:

ParameterTypeDescription
$keystringCache key in the current storage.
$withMetadataboolInclude 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): array

Parameters:

ParameterTypeDescription
$keysstring[]Keys in the current storage.
$withMetadataboolInclude 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
): bool

Parameters:

ParameterTypeDescription
$keystringCache key in the current storage.
$contentmixedValue to store.
$expirationDateTimeInterface\|int\|nullExpiration or null to use the configured setting.
$expireAfterDateInterval\|int\|nullRelative expiration or null to use the configured setting.
$lockboolLock 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): bool

Parameters:

ParameterTypeDescription
$keystringCache 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): bool

Parameters:

ParameterTypeDescription
$keystringCache 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): bool

Parameters:

ParameterTypeDescription
$keystringCache 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): bool

Parameters:

ParameterTypeDescription
$keystringCache key in the current storage.
$gcExpiredLocksboolBypass 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): bool

Parameters:

ParameterTypeDescription
$keysiterable<string>Keys to delete.
$gcExpiredLocksboolBypass 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): bool

Parameters:

ParameterTypeDescription
$keysstring[]Keys in the current storage.
$storagestring\|nullOptional storage name. Null uses the current storage.

Return:

bool - Returns true if Redis deletes at least one key.