laminas/laminas-cache
Laminas Cache provides flexible caching for PHP applications, with adapters for common backends, cache storage, patterns, plugins, and PSR-compatible integrations. Includes tools for configuring, managing, and testing cache behavior in Laminas apps.
Storage adapters are wrappers for real storage resources such as memory or the filesystem, using the well known adapter pattern.
They come with tons of methods to read, write, and modify stored items, and to get information about stored items and the storage.
All adapters implement Laminas\Cache\Storage\StorageInterface, and most extend
Laminas\Cache\Storage\Adapter\AbstractAdapter, which provides a foundation of
common logic.
Configuration is handled by either Laminas\Cache\Storage\Adapter\AdapterOptions,
or an adapter-specific options class if it exists. You may pass the options
instance to the class at instantiation, via the setOptions() method, or,
alternately, pass an associative array of options in either place (internally,
these are then passed to an options class instance). Alternately, you can pass associative array to the
Laminas\Cache\Service\StorageAdapterFactoryInterface::create method.
Caching adapters can either be created from the provided
Laminas\Cache\Service\StorageAdapterFactoryInterface, or by instantiating one of the
Laminas\Cache\Storage\Adapter\* classes. To make life easier, the
Laminas\Cache\Service\StorageAdapterFactoryInterface comes with a create() method to create an adapter
and all requested plugins at once.
use Laminas\Cache\Service\StorageAdapterFactoryInterface;
use Laminas\Cache\Service\StoragePluginFactoryInterface;
use Psr\Container\ContainerInterface;
/** [@var](https://github.com/var) ContainerInterface $container */
$container = null; // can be any configured PSR-11 container
/** [@var](https://github.com/var) StorageAdapterFactoryInterface $storageFactory */
$storageFactory = $container->get(StorageAdapterFactoryInterface::class);
// Via factory:
$cache = $storageFactory->create(
'apcu',
['ttl' => 3600],
[
[
'name' => 'exception_handler',
'options' => [
'throw_exceptions' => false,
],
],
]
);
// Via array configuration:
$cache = $storageFactory->createFromArrayConfiguration([
'adapter' => 'apcu',
'options' => ['ttl' => 3600],
'plugins' => [
[
'name' => 'exception_handler',
'options' => [
'throw_exceptions' => false,
],
],
],
]);
// Alternately, create the adapter and plugin separately:
$cache = $storageFactory->create('apcu', ['ttl' => 3600]);
$pluginFactory = $container->get(StoragePluginFactoryInterface::class);
$plugin = $pluginFactory->create('exception_handler', [
'throw_exceptions' => false,
]);
$cache->addPlugin($plugin);
// Or do it completely manually:
$cache = new Laminas\Cache\Storage\Adapter\Apcu();
$cache->getOptions()->setTtl(3600);
$plugin = new Laminas\Cache\Storage\Plugin\ExceptionHandler();
$plugin->getOptions()->setThrowExceptions(false);
$cache->addPlugin($plugin);
Many Methods throw Exceptions
Because many caching operations throw an exception on error, you need to catch them. You can do so manually, or you can use the plugin
Laminas\Cache\Storage\Plugin\ExceptionHandlerwiththrow_exceptionsset tofalseto automatically catch them. You can also define anexception_callbackto log exceptions.
The following configuration options are defined by Laminas\Cache\Storage\Adapter\AdapterOptions and
are available for every supported adapter. Adapter-specific configuration options are described on
adapter level below.
| Option | Data Type | Default Value | Description |
|---|---|---|---|
ttl |
integer |
0 |
Time to live |
namespace |
string |
"laminascache" |
The “namespace” in which cache items will live |
key_pattern |
null|string |
null |
Pattern against which to validate cache keys |
readable |
boolean |
true |
Enable/Disable reading data from cache |
writable |
boolean |
true |
Enable/Disable writing data to cache |
Laminas\Cache\Storage\StorageInterface is the basic interface implemented by all
storage adapters.
namespace Laminas\Cache\Storage;
use Laminas\Cache\Storage\Adapter\AdapterOptions;
use Traversable;
interface StorageInterface
{
public function setOptions(AdapterOptions|iterable $options): self;
public function getOptions(): AdapterOptions;
/**
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function getItem(string $key, bool|null &$success = null, mixed &$casToken = null): mixed;
/**
* [@param](https://github.com/param) non-empty-list<non-empty-string> $keys
* [@return](https://github.com/return) array<non-empty-string,mixed> Associative array of keys and values
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function getItems(array $keys);
/**
* Test if an item exists.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function hasItem(string $key): bool;
/**
* Test multiple items.
*
* [@param](https://github.com/param) non-empty-array<non-empty-string> $keys
* [@return](https://github.com/return) list<non-empty-string> Array of found keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function hasItems(array $keys): array;
/**
* Store an item.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function setItem(string $key, mixed $value): bool;
/**
* Store multiple items.
*
* [@param](https://github.com/param) non-empty-array<non-empty-string,mixed> $keyValuePairs
* [@return](https://github.com/return) list<non-empty-string> Array of not stored keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function setItems(array $keyValuePairs): array;
/**
* Add an item.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function addItem(string $key, mixed $value): bool;
/**
* Add multiple items.
*
* [@param](https://github.com/param) non-empty-array<non-empty-string,mixed> $keyValuePairs
* [@return](https://github.com/return) list<non-empty-string> Array of not stored keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function addItems(array $keyValuePairs): array;
/**
* Replace an existing item.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function replaceItem(string $key, mixed $value): bool;
/**
* Replace multiple existing items.
*
* [@param](https://github.com/param) non-empty-array<non-empty-string,mixed> $keyValuePairs
* [@return](https://github.com/return) list<non-empty-string> Array of not stored keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function replaceItems(array $keyValuePairs): array;
/**
* Set an item only if token matches
*
* It uses the token received from getItem() to check if the item has
* changed before overwriting it.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
* [@see](https://github.com/see) getItem()
* [@see](https://github.com/see) setItem()
*/
public function checkAndSetItem(mixed $token, string $key, mixed $value): bool;
/**
* Reset lifetime of an item
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function touchItem(string $key): bool;
/**
* Reset lifetime of multiple items.
*
* [@param](https://github.com/param) non-empty-list<non-empty-string> $keys
* [@return](https://github.com/return) list<non-empty-string> Array of not updated keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function touchItems(array $keys): array;
/**
* Remove an item.
*
* [@param](https://github.com/param) non-empty-string $key
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function removeItem(string $key): bool;
/**
* Remove multiple items.
*
* [@param](https://github.com/param) non-empty-array<non-empty-string> $keys
* [@return](https://github.com/return) list<non-empty-string> Array of not removed keys
* [@throws](https://github.com/throws) \Laminas\Cache\Exception\ExceptionInterface
*/
public function removeItems(array $keys): array;
public function getCapabilities(): Capabilities;
}
Laminas\Cache\Storage\AvailableSpaceCapableInterface implements a method to allow
retrieving the current available space remaining in storage.
namespace Laminas\Cache\Storage;
interface AvailableSpaceCapableInterface
{
/**
* Get available space in bytes
*/
public function getAvailableSpace(): int;
}
Laminas\Cache\Storage\TotalSpaceCapableInterface implements a method to allow
retrieving the total storage space.
namespace Laminas\Cache\Storage;
interface TotalSpaceCapableInterface
{
/**
* Get total space in bytes
*/
public function getTotalSpace(): int;
}
Laminas\Cache\Storage\ClearByNamespaceInterface implements a method to allow
clearing all cached items within a given namespace.
namespace Laminas\Cache\Storage;
interface ClearByNamespaceInterface
{
/**
* Remove items of given namespace
*
* [@param](https://github.com/param) non-empty-string $namespace
*/
public function clearByNamespace(string $namespace): bool;
}
Laminas\Cache\Storage\ClearByPrefixInterface implements a method to allow
clearing all cached items that have a given prefix (within the currently
configured namespace).
namespace Laminas\Cache\Storage;
interface ClearByPrefixInterface
{
/**
* Remove items matching given prefix
*
* [@param](https://github.com/param) non-empty-string $prefix
*/
public function clearByPrefix(string $prefix): bool;
}
Laminas\Cache\Storage\ClearExpiredInterface implements a method to allow clearing
all expired items (within the current configured namespace).
namespace Laminas\Cache\Storage;
interface ClearExpiredInterface
{
/**
* Remove expired items
*/
public function clearExpired(): bool;
}
Laminas\Cache\Storage\FlushableInterface implements a method for flushing the
entire cache storage.
namespace Laminas\Cache\Storage;
interface FlushableInterface
{
/**
* Flush the whole storage
*/
public function flush(): bool;
}
Laminas\Cache\Storage\IterableInterface implements a method for retrieving an
iterator of all items in storage. It extends IteratorAggregate, so it's
possible to directly iterate over the storage implementations that implement
this interface using foreach.
namespace Laminas\Cache\Storage;
use IteratorAggregate;
/**
* [@template-covariant](https://github.com/template-covariant) TKey
* [@template-covariant](https://github.com/template-covariant) TValue
* [@template-extends](https://github.com/template-extends) IteratorAggregate<TKey,TValue>
*/
interface IterableInterface extends IteratorAggregate
{
public function getIterator(): IteratorInterface;
}
Laminas\Cache\Storage\OptimizableInterface implements a method for running
optimization processes on the storage adapter.
namespace Laminas\Cache\Storage;
interface OptimizableInterface
{
/**
* Optimize the storage
*/
public function optimize(): bool;
}
Laminas\Cache\Storage\TaggableInterface implements methods for tagging items, and
cleaning (expiring) items matching tags.
namespace Laminas\Cache\Storage;
interface TaggableInterface
{
/**
* Set tags to an item by given key.
* An empty array will remove all tags.
*
* [@param](https://github.com/param) non-empty-string $key
* [@param](https://github.com/param) string[] $tags
*/
public function setTags(string $key, array $tags): bool;
/**
* Get tags of an item by given key
*
* [@param](https://github.com/param) non-empty-string $key
* [@return](https://github.com/return) string[]|false
*/
public function getTags(string $key): array|false;
/**
* Remove items matching given tags.
*
* If $disjunction only one of the given tags must match
* else all given tags must match.
*
* [@param](https://github.com/param) string[] $tags
*/
public function clearByTags(array $tags, bool $disjunction = false): bool;
}
Laminas\Cache\Storage\Adapter\Apcu stores cache items in shared memory through the
PHP extension APCu (Alternative PHP Cache).
This adapter implements the following interfaces:
Laminas\Cache\Storage\StorageInterfaceLaminas\Cache\Storage\AvailableSpaceCapableInterfaceLaminas\Cache\Storage\ClearByNamespaceInterfaceLaminas\Cache\Storage\ClearByPrefixInterfaceLaminas\Cache\Storage\FlushableInterfaceLaminas\Cache\Storage\IterableInterfaceLaminas\Cache\Storage\TotalSpaceCapableInterface| Capability | Value |
|---|---|
supportedDatatypes |
null, bool, int, float, string, array (serialized), object (serialized) |
ttlSupported |
true |
ttlPrecision |
1 |
usesRequestTime |
value of apc.use_request_time INI value, disabled by default. |
maxKeyLength |
5182 |
namespaceIsPrefix |
true |
The APCu adapter does provide a couple of metadatas, which can be fetched by by using either MetadataCapableInterface#getMetadata or MetadataCapableInterface#getMetadatas.
It will return an object with the following properties (or null):
| Metadata | Type | Description |
|---|---|---|
internalKey |
string |
The internal key used to store the cache item |
lastAccessTime |
int |
The time the cache item was last accessed |
creationTime |
int |
The time the cache item was created |
lastModifiedTime |
int |
The time the cache item was last modified |
size |
int |
The size the cache item is consuming within the cache |
hits |
int |
The amount of times the item was requested and returned from the backend |
timeToLive |
int |
The overall time to live (in seconds) the cache item was persisted for |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
namespace_separator |
string |
":" | A separator for the namespace and prefix. |
Laminas\Cache\Storage\Adapter\BlackHole does not store any cache items. This adapter is useful to bypass caching behavior. This might be the case in development mode or unit testing.
This adapter implements the following interfaces:
Laminas\Cache\Storage\StorageInterfaceLaminas\Cache\Storage\AvailableSpaceCapableInterfaceLaminas\Cache\Storage\ClearByNamespaceInterfaceLaminas\Cache\Storage\ClearByPrefixInterfaceLaminas\Cache\Storage\ClearExpiredInterfaceLaminas\Cache\Storage\FlushableInterfaceLaminas\Cache\Storage\IterableInterfaceLaminas\Cache\Storage\OptimizableInterfaceLaminas\Cache\Storage\TaggableInterfaceLaminas\Cache\Storage\TotalSpaceCapableInterface| Capability | Value |
|---|---|
supportedDatatypes |
null, bool, int, float, string, array, object |
ttlSupported |
true |
ttlPrecision |
1 |
usesRequestTime |
false |
maxKeyLength |
unlimited as nothing will be cached anyways |
namespaceIsPrefix |
true |
Laminas\Cache\Storage\Adapter\Filesystem stores cache items on the filesystem.
This adapter implements the following interfaces:
Laminas\Cache\Storage\StorageInterfaceLaminas\Cache\Storage\AvailableSpaceCapableInterfaceLaminas\Cache\Storage\ClearByNamespaceInterfaceLaminas\Cache\Storage\ClearByPrefixInterfaceLaminas\Cache\Storage\ClearExpiredInterfaceLaminas\Cache\Storage\FlushableInterfaceLaminas\Cache\Storage\IterableInterfaceLaminas\Cache\Storage\OptimizableInterfaceLaminas\Cache\Storage\TaggableInterfaceLaminas\Cache\Storage\TotalSpaceCapableInterface| Capability | Value |
|---|---|
supportedDatatypes |
string, null => string, boolean => string, integer => string, double => string |
ttlSupported |
true |
ttlPrecision |
1 |
usesRequestTime |
false |
maxKeyLength |
249 (this is the maximum, but depending on the namespace being used, the length might be lower) |
namespaceIsPrefix |
true |
| Metadata | Type | Description |
|---|---|---|
lastAccessTime |
int|null |
The time the cache item was last accessed |
creationTime |
int|null |
The time the cache item was created |
lastModifiedTime |
int|null |
The time the cache item was last modified |
filesize |
int|null |
The amount of bytes the cache item is consuming in the filesystem |
filespec |
string |
The absolute path to the cache file without suffix |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
namespace_separator |
string |
":" | A separator for the namespace and prefix |
cache_dir |
string |
"" | Directory to store cache files. |
clear_stat_cache |
boolean |
true |
Call clearstatcache() enabled? |
dir_level |
integer |
1 |
Defines how much sub-directories should be created. |
dir_permission |
integer|false |
0700 |
Set explicit permission on creating new directories. |
file_locking |
boolean |
true |
Lock files on writing. |
file_permission |
integer |
false |
0600 Set explicit permission on creating new files. |
key_pattern |
string |
/^[a-z0-9_\+\-]*$/Di |
Validate key against pattern. |
no_atime |
boolean |
true |
Don’t get fileatime as atime on metadata. |
no_ctime |
boolean |
true... |
How can I help you explore Laravel packages today?