Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laminas Cache Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package and a storage adapter (e.g., filesystem):
    composer require laminas/laminas-cache laminas/laminas-cache-storage-adapter-filesystem
    
  2. Configure the cache in config/autoload/cache.global.php:
    return [
        'caches' => [
            'default-cache' => [
                'adapter' => Laminas\Cache\Storage\Adapter\Filesystem::class,
                'options' => [
                    'cache_dir' => __DIR__ . '/../../data/cache',
                ],
            ],
        ],
    ];
    
  3. Inject the cache into a controller or service:
    use Laminas\Cache\Storage\StorageInterface;
    
    class MyController {
        public function __construct(private StorageInterface $cache) {}
    }
    

First Use Case: Caching Expensive Operations

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);
}

Implementation Patterns

1. PSR-16 Integration (SimpleCache)

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

2. Dependency Injection

  • Controllers: Use ConfigAbstractFactory to resolve cached services:
    'controllers' => [
        'factories' => [
            MyController::class => ConfigAbstractFactory::class,
        ],
    ],
    
  • Services: Inject StorageInterface directly.

3. Cache Strategies

  • Output Caching: Cache entire responses (e.g., in middleware):
    $response = $this->cache->getItem('response_key');
    if (!$response) {
        $response = $this->dispatch();
        $this->cache->setItem('response_key', $response, 300);
    }
    return $response;
    
  • Class/Object Caching: Use Laminas\Cache\Storage\Plugin\Serializer for complex objects.

4. Tagging and Events

  • Tag-based invalidation: Use 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
    

Gotchas and Tips

1. Serialization Pitfalls

  • Required for PSR-16: Adapters like Filesystem, Redis, or Memcache must use Serializer plugin:
    $this->cache->addPlugin(new Serializer());
    
  • Custom Objects: Ensure objects implement JsonSerializable or use unserialize()-compatible serialization.

2. TTL Handling

  • TTL Units: Use DateInterval for clarity (e.g., new DateInterval('P1D') for 1 day).
  • Default TTL: Set globally in adapter options:
    'options' => [
        'ttl' => 86400, // Default: 24 hours
    ],
    

3. Debugging

  • Check Cache Directory: Ensure cache_dir is writable (e.g., chmod -R 775 data/cache).
  • Log Exceptions: Enable throw_exceptions in ExceptionHandler plugin:
    $this->cache->addPlugin(new ExceptionHandler(['throw_exceptions' => true]));
    

4. Performance Tips

  • Memory Adapter: Use Memory for testing (non-persistent):
    $cache = $this->cacheFactory->create(Memory::class);
    
  • Benchmark: Compare adapters with phpbench:
    vendor/bin/phpbench run --report=aggregate
    

5. Common Errors

  • "Cache not found": Verify the cache name exists in config['caches'].
  • Serialization Errors: Use Serializer plugin or ensure data is JSON-serializable.
  • TTL Ignored: Check adapter-specific TTL handling (e.g., Redis uses expire).

6. Extending Laminas Cache

  • Custom Adapters: Implement StorageInterface or extend AbstractAdapter.
  • Plugins: Create plugins for cross-cutting concerns (e.g., logging, metrics).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai