Luminova Framework

PHP Luminova: Filecache Storage Caching System

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

Store reusable data in filesystem cache namespaces with expiration and optional item locks.

FileCache stores reusable values under /writeable/caches/filecache/. A persistent ID selects a subdirectory and a storage name selects a cache namespace within it.

Use setSerializerOption() to select serialization and optionally enable base64 encoding. Available modes are defined by the inherited SERIALIZER_* constants.

Note:The Luminova Database Builder class already includes a built-in caching mechanism. You can specify your preferred cache driver in the environment variable file. Additional caching implementations are only necessary if you're working directly with prepared statements or the Database connection object.


Class Definition

  • Full namespace: Luminova\Cache\FileCache
  • This class extends Luminova\Base\AbstractCache and inherits LazyObjectInterface.
  • This class is final.

Usage

use Luminova\Cache\FileCache;

$cache = new FileCache(storage: 'products', persistentId: 'catalog');

if ($cache->connect()) {
    $cache->expiresAfter(300)
        ->set('featured', ['sku-123']);

    $featured = $cache->getItem('featured');
}

Refresh a Cached Value

Set an expiration policy before calling onExpired(). It uses a valid cached value or calls your loader and caches its nonempty result. In this example, the function accepts a loader that can query a database or read another data source.

use Luminova\Cache\FileCache;

function loadCatalog(FileCache $cache, callable $readCatalog): array
{
    if (!$cache->connect()) {
        return $readCatalog();
    }

    return $cache->expiresAfter(300)
        ->onExpired('catalog', $readCatalog);
}

$cache = new FileCache(storage: 'products', persistentId: 'catalog');

$catalog = loadCatalog(
    $cache, 
    static fn (): array => ['sku-123', 'sku-456']
);

Write, Read, and Invalidate a Batch

use Luminova\Cache\FileCache;

$cache = new FileCache(storage: 'inventory', persistentId: 'catalog');

if ($cache->connect()) {
    $saved = $cache->setItems([
        'sku-123' => ['quantity' => 5],
        'sku-456' => ['quantity' => 12],
    ], expireAfter: 120);

    if ($saved === 2) {
        $inventory = $cache->getItems(['sku-123', 'sku-456']);
    }

    // After a stock update, remove the affected key from the cache.
    $cache->deleteItems(['sku-123']);
}

Constants

These constants define default cache expiration times in seconds. They can be used throughout the application wherever cache TTL (time-to-live) is needed.

ConstantTypeValueDescription
TTL_7DAYSint7 24 60 * 60Represents 7 days in seconds
TTL_24HRint24 60 60Represents 24 hours in seconds
TTL_30MINint30 * 60Represents 30 minutes in seconds

Methods

__construct

Create a cache with an optional storage name and persistent ID.

public function __construct(?string $storage = null, ?string $persistentId = null)

Parameters:

ParameterTypeDescription
$storagestring|nullThe cache storage name (default: null).
$persistentIdstring|nullOptional cache storage sub-directory (default: null).

Throws:

Note:If your didn't specify the storage name on initialization, then you must call setStorage method later before accessing caches.


getInstance

Get a static singleton instance of cache class.

public static function getInstance(
    ?string $storage = null,
    ?string $persistentId = null
): self

Parameters:

ParameterTypeDescription
$storagestring|nullThe cache storage name (default: null).
$persistentIdstring|nullOptional cache storage sub directory (default: null).

Throws:


getPath

Gets the cache full storage filename.

public function getPath(): ?string

Return:

string - Return the cache storage filename.


getRoot

Gets the cache storage root directory.

public function getRoot(): ?string

Return:

string - Return the cache storage directory.


setPersistentId

Set the persistent ID. A changed ID marks the current connection inactive. IDs accept letters, numbers, underscores, and hyphens. Pass an empty string to clear the ID.

public function setPersistentId(string $persistentId): self

Parameters:

ParameterTypeDescription
$persistentIdstringPersistent ID. FileCache uses it as a relative subdirectory.

Return:

self - The cache instance.


setStorage

Sets the cache storage name.

public function setStorage(string $storage): self

Parameters:

ParameterTypeDescription
$storagestringThe cache storage name.

Return:

self - Return instance of memory cache class.


setExpire

Sets the expiration time of the cache item.

public function setExpire(DateTimeInterface|int|null $expiration = null): self

Parameters:

ParameterTypeDescription
$expiration\DateTimeInterface|int|nullThe expiration time of the cache item.

Return:

self - Return instance of memory cache class.

Note: When set to null, the item will never expire, when set to 0, it automatically expires immediately.


expiresAfter

Sets the expiration time of the cache item relative to the current time.

public function expiresAfter(DateInterval|int|null $after = null): self

Parameters:

ParameterTypeDescription
$after\DateInterval|int|nullThe expiration time in seconds or as a DateInterval.

Return:

self - Return instance of memory cache class.


setLock

Sets the cache lock to avoid deletion even when cache has expired.

public function setLock(bool $lock): self

Parameters:

ParameterTypeDescription
$lockboollock flag to be used.

Return:

self - Return instance of memory cache class.


hashStorage

Generate hash storage name for cache.

public static function hashStorage(string $storage): string

This method will generate a hash value of storage name which is same as the one used in storing cache items.

Parameters:

ParameterTypeDescription
$storagestringThe cache storage name to hash.

Return:

string - Return a hashed value of the specified storage name.

Throws:


configureGarbageCollection

Set enable or disable automatic deletion for expired caches.

public function configureGarbageCollection(
    bool $gcEnable,
    bool $gcExpiredLocks = false,
    int $interval = 300
): self

Parameters:

ParameterTypeDescription
$gcEnableboolEnable garbage collection.
$gcExpiredLocksboolAllow collecting expired locked entries (default false).
$intervalintMinimum interval for lazy collection, in seconds (default 300).

Return:

self - Return instance of file cache class.


onExpired

Retrieve the cache content, using the closure callback to update the content with new item if cache has expired.The closure is used to update new content when cache is expired, so the closure won't be executed until cache expires or empty.

public function onExpired(string $key, callable $onRefresh): mixed

Parameters:

ParameterTypeDescription
$keystringThe cache key, non-empty string.
$onRefresh\ClosureCallback function to refreshed cache when expired.
- The callback must return content to be cached.

Return:

mixed - Return cache content currently stored under key.

Throws:

Note:This method uses the expiration set using setExpire, expiresAfter and locking for setLock method.Additionally, this method will return only the the cache contents, metadata will be included.


getDelayed

Process items for the supplied keys with a callback. Use getItems() when you need an array of values.

If callback provided, it will be called with each retrieved item.The callback should accept two parameters: the cache instance and an array representing the retrieved cache item.

public function getDelayed(
    array $keys,
    bool $withCas = false,
    ?callable $onItem = null
): bool

Parameters:

ParameterTypeDescription
$keysarray<int, string>The array of cache keys to retrieve.
$withCasboolAccepted for API compatibility. File Cache does not supply CAS tokens.
$onItemcallable|nullOptional callback function (default: null).

Return:

bool - Returns true if the items were successfully retrieved, false otherwise.

Throws:


replace

Replace cache content with new data and expiration if necessary.This method replaces the existing cache item identified by the provided key with new content.

public function replace(string $key, mixed $content): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to replace content.
$contentmixedThe new content to update.

Return:

bool - Return true if item was successfully updated, otherwise false.

Throws:

Note: This method uses the expiration set using setExpire, expiresAfter and locking for setLock method.


getItem

Retrieve cache content from storage.This method retrieves the cache content associated with the specified key.Optionally, you can choose to return only the cached data or include metadata.

public function getItem(string $key, bool $withMetadata = false): mixed

Parameters:

ParameterTypeDescription
$keystringThe cache key to retrieve content for.
$withMetadataboolInclude metadata with the value (default false).

Return:

mixed - Returns the value or null in value mode. In metadata mode, a miss returns an empty item record with null data.

Throws:


getItems

Read multiple keys from the active storage.

public function getItems(array $keys, bool $withMetadata = false): array

Parameters:

ParameterTypeDescription
$keysstring[]Keys to retrieve.
$withMetadataboolInclude item metadata (default false).

Return:

array<string, mixed> - Results keyed by cache key.


set

Save item to cache storage.

public function set(string $key, mixed $content): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to use.
$contentmixedThe content to store in cache.

Return:

bool - Return true if cache was saved, otherwise false.

Throws:

Note: This method uses the options set using setExpire, expiresAfter and locking for setLock method.


setItem

Save an item to cache storage.This method stores the specified contents in the cache associated with the given key, expiration and optional locking to avoid deletion.

public function setItem(
    string $key,
    mixed $content,
    DateTimeInterface|int|null $expiration = 0,
    DateInterval|int|null $expireAfter = null,
    bool $lock = false
): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to use.
$contentmixedThe content to store in the cache.
$expiration\DateTimeInterface|int|nullThe cache expiration time.
If is provided, it will set the cache to expire after the specified duration.
If 0, the cache does not expire.
$expireAfter\DateInterval|int|nullSpecifies the exact cache expiration time after a certain period.
If null, it uses the $expiration parameter.
$lockboolWhether to lock the cache item to prevent deletion even when it expires (default: false).

Return:

bool - Returns true if the cache was successfully saved; otherwise, false.

Throws:


hasItem

Check if a cache key exists in storage.This method verifies if the cache item identified by the given key exists in the cache storage,it doesn't check expiration.

public function hasItem(string $key): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to check.

Return:

bool - Returns true if the cache key exists, otherwise false.


isLocked

Check if a cache item is locked to prevent deletion.

This method determines if the cache item identified by the given key is locked,which prevents it from being deleted. If the cache item does not exist, it is considered locked by default.

public function isLocked(string $key): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to check.

Return:

bool - Returns true if the item is locked or does not exist, otherwise, false.


hasExpired

Determine if a cache item has expired.This method checks if the cache item identified by the given key has expiredbased on its timestamp and expiration settings.

public function hasExpired(string $key): bool

Parameters:

ParameterTypeDescription
$keystringThe cache key to check for expiration.

Return:

bool - Returns true if the cache item has expired, otherwise false.

Note: If the cache key does not exist, it is considered expired and return true.


deleteItems

Use deleteItems([$key]) to remove a single key.

Delete multiple cache items by their keys.This method removes multiple cache items specified by an array of keys.

public function deleteItems(iterable $keys, bool $gcExpiredLocks = false): bool

Parameters:

ParameterTypeDescription
$keysiterable<int,string>The array of cache keys to delete.
$gcExpiredLocksboolAllow deletion even if the items are locked (default false).

Return:

bool - Returns true if at least one cache item was successfully deleted; otherwise, false.

Throws:


flush

Invalidate all cached items in the current cache storage directory and reset the internal pre-cached instance array to an empty state.

public function flush(): bool

Return:

bool - Returns true if the cache was successfully flushed, otherwise false.


clear

Clear all cached items in the current storage name and reset the internal pre-cached instance array to an empty state.

public function clear(): bool

Return:

bool - Returns true if the cache was successfully cleared, otherwise false.


delete

Delete multiple cache items associated with given keys from a specified storage.This method removes cache items based on their keys from the specified storage, which is hashed to ensure proper storage distribution.

public function delete(array $keys, ?string $storage = null): bool

Parameters:

ParameterTypeDescription
$keysstring[]The array of cache keys to be deleted.
$storagestringThe storage identifier for which cache items should be deleted.

Return:

bool - Returns true if the cache items were successfully deleted; otherwise, false.

Throws:

Note:This method will remove item even if its was locked to prevent deletion.


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.


getConn

Look up the stream associated with the current cache storage.

public function getConn(): ?Stream

Return:

Stream|null - Returns the registered file stream or null.


connect

Reuse the registered stream or open the current storage file.

public function connect(): bool

Return:

bool - Returns true when a stream was established.


disconnect

Close the current stream and remove it from the cache connection pool.

public function disconnect(): bool

Return:

bool - Returns true after clearing the connection state.