PHP Luminova: PSR-Compliant Simple Cache Implementation
Use the PSR-16 cache interface through the optional Luminova PSR cache package.
Simple Cache is a straightforward caching interface defined by the PHP Framework Interop Group (PHP-FIG) as PSR-16. It provides a simplified way to manage cache items without requiring complex setups. In the Luminova framework, Simple Cache supports various storage drivers, including file systems and Memcached.
Package and Framework Versions
This reference describes version 1.4.0 of the separate nanoblocktech/psr-cache package. Use the examples with a framework release compatible with that package.
Installation
To use Luminova caching with PSR-16 Simple interface, install the PSR Cache module via Composer:
composer require nanoblocktech/psr-cache:1.4.0Concepts of Simple Cache:
Unlike the PSR-6 Cache Pool Interface, the Simple Cache class is designed for ease of implementation and use, making it suitable for developers seeking a quick caching solution.
Initializing Cache Pool
Create an instance of the cache pool by specifying an optional cache storage name, a storage subfolder (for file-based caching), or a persistent ID (for the Memcached driver). You can also select the storage driver type.
File System Driver Initialization
use Luminova\Psr\Cache\SimpleCache;
// Create a new instance with file-based caching
$simple = new SimpleCache('my_cache_storage', 'cache_subfolder', SimpleCache::FILECACHE);
// Or use the factory method
$simple = SimpleCache::withFileCache('my_cache_storage', 'cache_subfolder');Memcached Driver Initialization
use Luminova\Psr\Cache\SimpleCache;
// Create a new instance with Memcached
$simple = new SimpleCache('my_cache_storage', 'my_persistent_id', SimpleCache::MEMCACHED);
// Or use the factory method
$simple = SimpleCache::withMemCache('my_cache_storage', 'my_persistent_id');Usage Example
In this example, SimpleCache manages cached values, with the underlying storage being either a file system cache driver or a memory-based cache driver (like Memcached).
Check for Cache Existence Before Storing
To determine if a cache item exists, you can check if the returned data matches your custom DEFAULT or use method SimpleCache::has('key'). If it doesn't, retrieve the data from the database (or another source), set the cache content with an expiration time, and save it. If the cache item exists, use the cached data directly.
use DateInterval;
if (!$simple->has('cache_key')) {
// Data not found in cache, load from the database
$data = 'This is my cache data';
// Store the data in cache with a 1-hour expiration
$simple->set('cache_key', $data, new DateInterval('PT1H'));
} else {
// Retrieve data from cache
$data = $simple->get('cache_key');
}Retrieve a Cached Value
You can easily fetch the stored data from the cache using the cache key. If the item doesn't exist, a default value or null will be returned.
$data = $simple->get('cache_key', 'DEFAULT_NO_DATA');Store and Invalidate Several Values
With a SimpleCache instance from the compatible package setup above, set a shared TTL and provide a fallback for missing keys. Use the same keys to invalidate entries after the data changes.
$values = [
'catalog.featured' => ['sku-123'],
'catalog.categories' => ['lighting', 'office'],
];
if ($simple->setMultiple($values, 300)) {
foreach ($simple->getMultiple(array_keys($values), []) as $key => $value) {
printf("%s: %d entries\n", $key, count($value));
}
}
$simple->deleteMultiple(['catalog.featured', 'catalog.categories']);Class Definition
- Full namespace:
Luminova\Psr\Cache\SimpleCache - This class implements:\Psr\SimpleCache\CacheInterface
Constants
The following constants define the cache storage types available in the SimpleCache. These are used to specify which caching driver should be used when initializing the simple cache.
| Constant | Type | Value | Description |
|---|---|---|---|
MEMCACHED | string | 'memcached' | Represents the Memcached-based cache storage. |
FILECACHE | string | 'filesystem' | Represents the file system-based cache storage. |
Cache Pool Methods
__construct
Initializes psr simple cache instance using either a file-based cache, a memory-based cache (Memcached),or the driver specified by the preferred.cache.driver configuration if no driver is provided.
public function __construct(
string|null $storage = 'psr_cache_storage',
string|null $subfolderOrId = 'psr',
string|null $driver = self::FILECACHE
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | The cache storage name used to distinguish different cache pools or spaces. |
$subfolderOrId | string|null | Optional subfolder for file-based cache or persistent ID for Memcached. |
$driver | string|null | Optional cache driver. Defaults to SimpleCache::FILECACHE if not provided.Accepts SimpleCache::FILECACHE or SimpleCache::MEMCACHED. |
withFileCache
Creates or returns a singleton instance of the class using file-based caching.
public static function withFileCache(?string $storage = null, ?string $subfolder = null): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | Optional storage name to be used in the file cache. |
$subfolder | string|null | Optional subfolder name for file-based storage. |
Return:
Luminova\Psr\Cache\SimpleCache - Returns a singleton instance of the class with a file-based cache engine.
withMemCache
Creates or returns a singleton instance of the class using Memcached.
public static function withMemCache(?string $storage = null, ?string $persistent_id = null): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string|null | Optional storage name to be used in the Memcached engine. |
$persistent_id | string|null | Optional persistent ID for Memcached sessions. |
Return:
Luminova\Psr\Cache\SimpleCache - Returns a singleton instance of the class with a memory-based cache engine.
get
Fetches a value from the cache.
public function get(string $key, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The unique key of this item in the cache. |
$default | mixed | Default value to return if the key does not exist (default: null). |
Return:
mixed - Returns the value of the item from the cache, or $default in case of cache miss.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if the $key string is not a legal value.
set
Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
public function set(string $key, mixed $value, DateInterval|int|null $ttl = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The key of the item to store. |
$value | mixed | The value of the item to store. Must be serializable. |
$ttl | \DateInterval|int|null | Optional TTL value of this item (default: 24 hours). |
Return:
bool - Returns true on success and false on failure.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if the $key string is not a legal value.
has
Determines whether an item is present in the cache.
public function has(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The cache item key. |
Return:
bool - Returns true if cache key exists, otherwise false on failure.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if the $key string is not a legal value.
NOTE: It is recommended that
has()is only to be used for cache warming type purposes and not to be used within your live applications operations forget/set, as this method is subject to a race condition wherehas()will return true and immediately after,another script can remove it, making the state of your app out of date.
delete
Delete an item from the cache by its unique key.
public function delete(string $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The unique cache key of the item to delete. |
Return:
bool - Returns true if the item was successfully removed. False if there was an error.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if the $key string is not a legal value.
clear
Wipes clean the entire cache's keys.
public function clear(): boolReturn:
bool - Returns true on success and false on failure.
getMultiple
Obtains multiple cache items by their unique keys.
public function getMultiple(iterable $keys, mixed $default = null): iterableParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | iterable | A list of keys that can obtained in a single operation. |
$default | mixed | Default value to return for keys that do not exist (default: null). |
Return:
iterable - Return list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value.
setMultiple
Persists a set of key => value pairs in the cache, with an optional TTL.
public function setMultiple(iterable $values, DateInterval|int|null $ttl = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$values | iterable | A list of key => value pairs for a multiple-set operation. |
$ttl | \DateInterval|int|null | Optional TTL value of this item (default: 24 hours). |
Return:
bool - Return true on success and false on failure.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if $values is neither an array nor a Traversable, or if any of the $values are not a legal value.
deleteMultiple
Deletes multiple cache items in a single operation.
public function deleteMultiple(iterable $keys): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$keys | iterable | A list of string-based keys to be deleted. |
Return:
bool - Return true if the items were successfully removed. False if there was an error.
Throws:
Luminova\Psr\Cache\Exceptions\InvalidArgumentException - Throws if $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value.