PHP Luminova: Filecache Storage Caching System
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
Builderclass 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 theDatabaseconnection object.
Class Definition
- Full namespace:
Luminova\Cache\FileCache - This class extends
Luminova\Base\AbstractCacheand 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.
| Constant | Type | Value | Description |
|---|---|---|---|
TTL_7DAYS | int | 7 24 60 * 60 | Represents 7 days in seconds |
TTL_24HR | int | 24 60 60 | Represents 24 hours in seconds |
TTL_30MIN | int | 30 * 60 | Represents 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:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | The cache storage name (default: null). |
$persistentId | string|null | Optional cache storage sub-directory (default: null). |
Throws:
- Luminova\Exceptions\CacheException - if there is a problem loading the cache.
Note:If your didn't specify the storage name on initialization, then you must call
setStoragemethod later before accessing caches.
getInstance
Get a static singleton instance of cache class.
public static function getInstance(
?string $storage = null,
?string $persistentId = null
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | The cache storage name (default: null). |
$persistentId | string|null | Optional cache storage sub directory (default: null). |
Throws:
- Luminova\Exceptions\CacheException - if there is a problem loading the cache.
getPath
Gets the cache full storage filename.
public function getPath(): ?stringReturn:
string - Return the cache storage filename.
getRoot
Gets the cache storage root directory.
public function getRoot(): ?stringReturn:
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$persistentId | string | Persistent ID. FileCache uses it as a relative subdirectory. |
Return:
self - The cache instance.
setStorage
Sets the cache storage name.
public function setStorage(string $storage): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string | The 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$expiration | \DateTimeInterface|int|null | The 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$after | \DateInterval|int|null | The 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$lock | bool | lock 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): stringThis method will generate a hash value of storage name which is same as the one used in storing cache items.
Parameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string | The cache storage name to hash. |
Return:
string - Return a hashed value of the specified storage name.
Throws:
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache storage name is provided.
configureGarbageCollection
Set enable or disable automatic deletion for expired caches.
public function configureGarbageCollection(
bool $gcEnable,
bool $gcExpiredLocks = false,
int $interval = 300
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$gcEnable | bool | Enable garbage collection. |
$gcExpiredLocks | bool | Allow collecting expired locked entries (default false). |
$interval | int | Minimum 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key, non-empty string. |
$onRefresh | \Closure | Callback function to refreshed cache when expired. - The callback must return content to be cached. |
Return:
mixed - Return cache content currently stored under key.
Throws:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache key is provided.
Note:This method uses the expiration set using
setExpire,expiresAfterand locking forsetLockmethod.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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | array<int, string> | The array of cache keys to retrieve. |
$withCas | bool | Accepted for API compatibility. File Cache does not supply CAS tokens. |
$onItem | callable|null | Optional callback function (default: null). |
Return:
bool - Returns true if the items were successfully retrieved, false otherwise.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If a non-empty list contains an invalid cache key.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key to replace content. |
$content | mixed | The new content to update. |
Return:
bool - Return true if item was successfully updated, otherwise false.
Throws:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache key is provided.
Note: This method uses the expiration set using
setExpire,expiresAfterand locking forsetLockmethod.
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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key to retrieve content for. |
$withMetadata | bool | Include 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:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or error occurred while reading cache.
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache key is provided.
getItems
Read multiple keys from the active storage.
public function getItems(array $keys, bool $withMetadata = false): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | Keys to retrieve. |
$withMetadata | bool | Include 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key to use. |
$content | mixed | The content to store in cache. |
Return:
bool - Return true if cache was saved, otherwise false.
Throws:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache key is provided.
Note: This method uses the options set using
setExpire,expiresAfterand locking forsetLockmethod.
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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key to use. |
$content | mixed | The content to store in the cache. |
$expiration | \DateTimeInterface|int|null | The 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|null | Specifies the exact cache expiration time after a certain period. If null, it uses the $expiration parameter. |
$lock | bool | Whether 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:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
- Luminova\Exceptions\InvalidArgumentException - Throws if empty cache key is provided.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | iterable<int,string> | The array of cache keys to delete. |
$gcExpiredLocks | bool | Allow 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:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
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(): boolReturn:
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(): boolReturn:
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | The array of cache keys to be deleted. |
$storage | string | The storage identifier for which cache items should be deleted. |
Return:
bool - Returns true if the cache items were successfully deleted; otherwise, false.
Throws:
- Luminova\Exceptions\CacheException - Throws if error occurred while deleting items.
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): 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.
getConn
Look up the stream associated with the current cache storage.
public function getConn(): ?StreamReturn:
Stream|null - Returns the registered file stream or null.
connect
Reuse the registered stream or open the current storage file.
public function connect(): boolReturn:
bool - Returns true when a stream was established.
disconnect
Close the current stream and remove it from the cache connection pool.
public function disconnect(): boolReturn:
bool - Returns true after clearing the connection state.