laminas/laminas-cache
Laminas Cache provides flexible caching for PHP apps with storage adapters (memory, filesystem, Redis, etc.), plugins, and cache patterns. Includes PSR-6/PSR-16 support, configuration options, and utilities for improving performance and reducing expensive operations.
composer require laminas/laminas-cache laminas/laminas-cache-storage-adapter-filesystem
config/autoload/cache.global.php:
return [
'caches' => [
'default-cache' => [
'adapter' => Laminas\Cache\Storage\Adapter\Filesystem::class,
'options' => [
'cache_dir' => __DIR__ . '/../../data/cache',
],
],
],
];
use Laminas\Cache\Storage\StorageInterface;
class MyController {
public function __construct(private StorageInterface $cache) {}
}
public function indexAction() {
$key = 'expensive_operation_result';
if (!$this->cache->hasItem($key)) {
$result = $this->performExpensiveOperation();
$this->cache->setItem($key, $result, 3600); // Cache for 1 hour
}
return $this->cache->getItem($key);
}
Wrap Laminas Cache with SimpleCacheDecorator for PSR-16 compatibility:
use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;
$cache = new SimpleCacheDecorator($this->cache);
$value = $cache->get('key', $default);
$cache->set('key', $value, 3600); // TTL in seconds
ConfigAbstractFactory to resolve cached services:
'controllers' => [
'factories' => [
MyController::class => ConfigAbstractFactory::class,
],
],
StorageInterface directly.$response = $this->cache->getItem('response_key');
if (!$response) {
$response = $this->dispatch();
$this->cache->setItem('response_key', $response, 300);
}
return $response;
Laminas\Cache\Storage\Plugin\Serializer for complex objects.Laminas\Cache\Storage\Plugin\TagPlugin:
$this->cache->addPlugin(new TagPlugin());
$this->cache->addItem('user:1', $user, ['users']);
$this->cache->invalidateTags(['users']); // Clear all tagged items
Filesystem, Redis, or Memcache must use Serializer plugin:
$this->cache->addPlugin(new Serializer());
JsonSerializable or use unserialize()-compatible serialization.DateInterval for clarity (e.g., new DateInterval('P1D') for 1 day).'options' => [
'ttl' => 86400, // Default: 24 hours
],
cache_dir is writable (e.g., chmod -R 775 data/cache).throw_exceptions in ExceptionHandler plugin:
$this->cache->addPlugin(new ExceptionHandler(['throw_exceptions' => true]));
Memory for testing (non-persistent):
$cache = $this->cacheFactory->create(Memory::class);
phpbench:
vendor/bin/phpbench run --report=aggregate
config['caches'].Serializer plugin or ensure data is JSON-serializable.expire).StorageInterface or extend AbstractAdapter.How can I help you explore Laravel packages today?