PHP Luminova: Memcached Storage and Caching
Store and retrieve Luminova cache entries using a Memcached server.
The Luminova Memory Cache class extends PHP's Memcached to simplify caching by storing and retrieving cached content on the system's hard disk. This class allows you to cache reusable data locally or remotely, reducing the need for repetitive database queries or API calls. By caching responses, you can improve performance and efficiency when the same content is requested multiple times.
This class shares core methods with the File Cache class, making it easy to switch between memory and file system caching without altering existing code. However, the MemoryCache class includes some unique methods not available in Luminova\Cache\FileCache, and vice versa.
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\MemoryCache - This class extends
Luminova\Base\AbstractCacheand inherits LazyObjectInterface. - This class is final.
Setups
To setup the default memcached connection server, these are the environment variable keys required:
memcached.persistent.id = null(string|null) - Your application persistent Id.memcached.key.prefix = null(string|null) - Your application cache key prefix.memcached.host = localhost(string) - Your application cache hostname or IP address.memcached.port = 11211(int) - Your application port number on which the cache server is listening.memcached.server.weight = 0(int) - The server connection weight.
Usage
Connect and Cache a Lookup
Use the configured Memcached server and set a TTL in seconds. The example leaves the database lookup to the caller so it can run even when the cache connection is unavailable.
use Luminova\Cache\MemoryCache;
function loadProduct(MemoryCache $cache, string $sku, callable $readProduct): array
{
if (!$cache->connect()) {
return $readProduct($sku);
}
return $cache->expiresAfter(300)->onExpired(
'product:' . $sku,
static fn (): array => $readProduct($sku)
);
}
$cache = new MemoryCache(storage: 'products', persistentId: 'catalog');
$product = loadProduct(
$cache,
'sku-123',
static fn (string $sku): array => ['sku' => $sku, 'name' => 'Desk lamp']
);Read Multiple Keys With a Delayed Lookup
Use an already connected MemoryCache instance initialized with a storage name. fetchResult() collects the buffered results after a successful getDelayed() call.
$products = [];
if ($cache->getDelayed(['product:sku-123', 'product:sku-456'])) {
$products = $cache->fetchResult();
}Methods
You can initialize the cache using the global cache helper function:
$cache = cache('memcached', 'products');For more information on implementing cache features in your application, refer to the Environment Configuration Variables.
__construct
Initializes memcache extension class instance with an optional storage name and an optional persistent ID.
public function __construct(?string $storage = null, ?string $persistentId = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | The cache storage name (default: null). If null, you must call create method later. |
$persistentId | string|null | Optional unique ID for persistent connections (default: null). - If null is specified, will used the default persistent id from environment variables. - If not set in environment variables default will be used instead. |
Throws:
- Luminova\Exceptions\CacheException - if there is an issue loading the cache.
getInstance
Retrieves or creates a singleton instance of the memcache extension class.
public static function getInstance(
?string $storage = null,
?string $persistentId = null
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | The cache storage name (default: null). If null, you must call create method later. |
$persistentId | string|null | Optional unique ID for persistent connections (default: null). - If null is specified, will used the default persistent id from environment variables. - If not set in environment variables default will be used instead. |
Return:
static - The singleton instance of the cache.
Throws:
- Luminova\Exceptions\CacheException - if there is an issue loading the cache.
getConn
Retrieves the current connection instance of the cache Memcached being used.
public function getConn(): ?MemcachedReturn:
\Memcached|null - Return the instance of Memcached, otherwise null.
getPersistentId
Retrieves the current connection persistent id being used.
public function getPersistentId(): ?stringReturn:
string|null - Return the persistent d=id, otherwise null.
addServer
Adds a server to the cache configuration.
public function addServer(string $host, int $port, int $weight = 0): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$host | string | The server hostname or IP address. |
$port | int | The server port number. |
$weight | int | Optional weight for the server (default: 0). |
Return:
self - Returns the memory cache instance.
Note: After setting server you should call
reconnectmethod to connect to new servers.
setServers
Sets multiple servers in the cache configuration.
public function setServers(array $servers): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$servers | array<int, string|int> | An array of server configurations where each element is an array [host, port, weight]. |
Return:
self - Returns the memory cache instance.
Note: After setting servers you should call
reconnectmethod to connect to new servers.
setOption
Sets an option for the cache.
public function setOption(int $option, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$option | int | The option to set. |
$value | mixed | The value for the option. |
Return:
self - Returns the memory cache instance.
connect
Connects to the Memcached server(s) using the configured settings.Initializes a connection to the Memcached server(s) with the configured host, port, and weight, or using the provided server configuration.
public function connect(): boolReturn:
bool - Returns true if the connection is successful, false otherwise.
reconnect
Reconnect, closes the connection to the memcached server and initialize a new connection.
public function reconnect(): boolReturn:
bool - Returns true if the connection is successful, otherwise false.
disconnect
Closes the connection to the memcached server.If no connection exists, the method will return true immediately.
public function disconnect(): boolReturn:
bool - Returns true if the disconnection is successful or if no connection was open.
isResultCode
Check if result code matches with a given code.
public function isResultCode(array|int $code = Memcached::RES_SUCCESS): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$code | int|int[] | Result code or list of acceptable result codes (default Memcached::RES_SUCCESS). |
Return:
bool - Returns true if the result code matches, otherwise false.
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.
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.
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.
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.
fetchResult
Read the current delayed lookup results after calling getDelayed().
public function fetchResult(): arrayReturn:
array<array-key, mixed> - The buffered results.
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
Retrieve cache items for the given keys. If items are successfully retrieved, an optional callback can be invokedwith the retrieved data. Use getItems or getNext to access the retrieved items, or call reset to reset the iterator position to the start.
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 | Optional memcached specific feature. If true, CAS tokens will be used for retrieval (default: false). |
$onItem | callable|null | Optional callback function (default: null). |
Return:
bool - Returns true if the items were successfully retrieved, false otherwise.
Throws:
- Luminova\Exceptions\InvalidArgumentException - Throws if keys is empty array.
Note:The callback function should accept two parameters: the cache instance and an array of the retrieved cache item.To modify the item and have the changes reflected in
getItemsorgetNext, pass the item array by reference.
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 cache content if the key is valid and not expired otherwise, returns null if $withMetadata is true.
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. For results from a delayed lookup, use fetchResult() instead.
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.
fetchNext
Retrieves the next item from the delay execute method if available.
public function fetchNext(): ?arrayReturn:
array<array-key, mixed>|false - Return the next item or null if there are no more items.
Note: before calling this method, you must first call the
executemethod.
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.
deleteItem
Delete a specific cache item by key.This method removes the cache item associated with the given key.
public function deleteItem(string $key, bool $gcExpiredLocks = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache key of the item to delete. |
$gcExpiredLocks | bool | Allow deletion even if this item is locked (default false). |
Return:
bool - Returns true if the cache item was successfully deleted, otherwise false.
Throws:
- Luminova\Exceptions\CacheException - Throws if called without any storage name specified or unable to store cache.
deleteItems
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 memcached server 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, whichis 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.
ping
Check the active Memcached connection by attempting to write and read the diagnostic key __ping__, with a ten-second lifetime.
public function ping(): ?stringReturn:
string|null - Returns the diagnostic value when it can be read, or null when the connection or operation fails.