Luminova Framework

PHP Luminova: Memcached Storage and Caching

Last updated: 2025-11-24 16:55:12

The MemoryCache is an enhanced extension of Memcached, designed to simplify caching operations by leveraging local and remote servers to reduce the need for repetitive database queries.

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 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

  • Class namespace: Luminova\Cache\MemoryCache
  • Parent class: Luminova\Base\Cache
  • This class is marked as final and can't be subclassed

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.

Methods

You can initialize the cache using the global cache helper function:

$cache = cache('memcached');

For more information on implementing cache features in your application, refer to the Cache Examples Documentation.


constructor

Initializes memcache extension class instance with an optional storage name and an optional persistent ID.

public __construct(string|null $storage = null, string|null $persistent_id = null): mixed

Parameters:

ParameterTypeDescription
$storagestring|nullThe cache storage name (default: null). If null, you must call create method later.
$persistent_idstring|nullOptional 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:


getInstance

Retrieves or creates a singleton instance of the memcache extension class.

public static getInstance(?string $storage = null, ?string $persistent_id = null): static

Parameters:

ParameterTypeDescription
$storagestring|nullThe cache storage name (default: null). If null, you must call create method later.
$persistent_idstring|nullOptional 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 Value:

static - The singleton instance of the cache.

Throws:


getConn

Retrieves the current connection instance of the cache Memcached being used.

public getConn(): ?\Memcached

Return Value:

\Memcached|null - Return the instance of Memcached, otherwise null.


getId

Retrieves the current connection persistent id being used.

public getId(): ?string

Return Value:

string|null - Return the persistent d=id, otherwise null.


setServer

Adds a server to the cache configuration.

public setServer(string $host, int $port, int $weight): self

Parameters:

ParameterTypeDescription
$hoststringThe server hostname or IP address.
$portintThe server port number.
$weightintOptional weight for the server (default: 0).

Return Value:

self - Returns the memory cache instance.

Note: After setting server you should call reconnect method to connect to new servers.


setServers

Sets multiple servers in the cache configuration.

public setServers(array<int,string|int> $config): self

Parameters:

ParameterTypeDescription
$configarray<int,string|int>An array of server configurations where each element is an array [host, port, weight].

Return Value:

self - Returns the memory cache instance.

Note: After setting servers you should call reconnect method to connect to new servers.


setOption

Sets an option for the cache.

public setOption(int $option, mixed $value): self

Parameters:

ParameterTypeDescription
$optionintThe option to set.
$valuemixedThe value for the option.

Return Value:

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

Return Value:

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

Return Value:

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

Return Value:

bool - Returns true if the disconnection is successful or if no connection was open.


is

Check if result code matches with a given code.

public is(int $resultCode = Memcached::RES_SUCCESS): bool

Parameters:

ParameterTypeDescription
$resultCodeintThe memcached result code (default: Memcached::RES_SUCCESS).

Return Value:

bool - Returns true if the result code matches, otherwise false.


setStorage

Sets the cache storage name.

public setStorage(string $storage): self

Parameters:

ParameterTypeDescription
$storagestringThe cache storage name.

Return Value:

self - Return instance of memory cache class.

Throws:


hashStorage

Generate hash storage name for cache.

public static 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 Value:

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

Throws:


setExpire

Sets the expiration time of the cache item.

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

Parameters:

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

Return Value:

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 expiresAfter(\DateInterval|int|null $after): self

Parameters:

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

Return Value:

self - Return instance of memory cache class.


setLock

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

public setLock(bool $lock): self

Parameters:

ParameterTypeDescription
$lockboollock flag to be used.

Return Value:

self - Return instance of memory cache class.


enableDeleteExpired

Set enable or disable automatic deletion for expired caches.

public enableDeleteExpired(bool $allow, bool $includeLocked = false): self

Parameters:

ParameterTypeDescription
$allowboolThe deletion flag.
$includeLockedboolOptional specify whether to also delete locked caches (default: true).

Return Value:

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 onExpired(string $key, \Closure $callback): mixed

Parameters:

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

Return Value:

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.


execute

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 execute(array<int,string> $keys, bool $withCas = false, ?callable $callback = null): bool

Parameters:

ParameterTypeDescription
$keysarray<int,string>The array of cache keys to retrieve.
$withCasboolOptional memcached specific feature. If true, CAS tokens will be used for retrieval (default: false).
$callbackcallable|nullOptional callback function (default: null).

Return Value:

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

Throws:

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 getItems or getNext, 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 replace(string $key, mixed $content): bool

Parameters:

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

Return Value:

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 getItem(string $key, bool $onlyContent = true): mixed

Parameters:

ParameterTypeDescription
$keystringThe cache key to retrieve content for.
$onlyContentboolWhether to return only the cache content or include metadata (default: true).

Return Value:

mixed - Returns the cache content if the key is valid and not expired otherwise, returns null if $onlyContent is true