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

  1. Installation:

    composer require laminas/laminas-cache laminas/laminas-cache-storage-adapter-filesystem
    

    (Use other adapters like redis, memcached, or apcu as needed.)

  2. Basic Cache Usage:

    use Laminas\Cache\Storage\Adapter\Filesystem;
    use Laminas\Cache\Storage\Plugin\Serializer;
    
    // Create a filesystem adapter
    $cache = new Filesystem([
        'cache_dir' => storage_path('framework/cache'),
    ]);
    
    // Add serializer plugin for non-string data
    $cache->addPlugin(new Serializer());
    
    // Set and get a value
    $cache->setItem('key', ['data' => 'value'], 3600); // TTL: 1 hour
    $value = $cache->getItem('key');
    
  3. PSR-16 Compatibility (SimpleCache):

    use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;
    
    $psr16Cache = new SimpleCacheDecorator($cache);
    $psr16Cache->set('psr_key', 'psr_value', 3600);
    $psrValue = $psr16Cache->get('psr_key');
    

Implementation Patterns

1. Dependency Injection in Laravel

Leverage Laravel's service container to register and resolve cache adapters:

// In a service provider (e.g., AppServiceProvider)
$this->app->singleton('cache.filesystem', function ($app) {
    return new Filesystem([
        'cache_dir' => storage_path('framework/cache'),
    ]);
});

// Resolve in a controller
public function __construct(private $cache) {
    $this->cache = $this->cache->filesystem;
}

2. Caching Strategies

  • Output Caching (e.g., views):

    $cacheKey = 'view_homepage_' . md5($request->getPathInfo());
    if ($this->cache->hasItem($cacheKey)) {
        return $this->cache->getItem($cacheKey);
    }
    $content = view('home')->render();
    $this->cache->setItem($cacheKey, $content, 3600);
    return $content;
    
  • Class/Object Caching:

    $expensiveObject = $this->cache->getItem('expensive_object');
    if (!$expensiveObject) {
        $expensiveObject = new ExpensiveClass();
        $this->cache->setItem('expensive_object', $expensiveObject, 86400);
    }
    

3. Tag-Based Cache Invalidation

Use tags to invalidate related cache items:

// Set with tags
$this->cache->setItem('user_123', $userData, 3600, ['users', 'user_123']);

// Clear by tag
$this->cache->clean(['users']);

// Clear specific item
$this->cache->removeItem('user_123');

4. Fallback Logic with PSR-16

$value = $this->cache->get('key', function () {
    return computeExpensiveValue();
});

5. Multi-Adapter Setup

Configure multiple adapters (e.g., filesystem + Redis) and switch dynamically:

// In config/cache.php
'default' => [
    'driver' => 'filesystem',
    'options' => ['cache_dir' => storage_path('framework/cache')],
],
'redis' => [
    'driver' => 'redis',
    'options' => ['host' => '127.0.0.1', 'port' => 6379],
],

Gotchas and Tips

1. Serialization Pitfalls

  • Non-Serializable Data: Objects with circular references or non-serializable properties (e.g., resources, closures) will fail. Use Serializer plugin or implement __serializeMagic()/__unserializeMagic().
  • Debugging: Check for Laminas\Cache\Exception\ExceptionInterface when serialization fails.

2. TTL Handling

  • TTL Units: Always specify TTL in seconds (integer) or DateInterval (e.g., new DateInterval('P1D') for 1 day).
  • Precision: Avoid fractional seconds; adapters may truncate.

3. Adapter-Specific Quirks

Adapter Notes
Filesystem Ensure cache_dir is writable. Use absolute paths.
Redis Requires predis/predis or phpredis. Configure connection options.
APCu Shared-memory; not suitable for clustered environments.
Memcached Requires memcached extension. Use consistent hashing for clusters.

4. PSR-16 Compliance

  • Delete Behavior: delete() returns false on failure (not null or exception). Audit plugins if using custom adapters.
  • Thread Safety: PSR-16 caches are not thread-safe by default. Use locks for concurrent writes:
    $lock = $this->cache->getLock('my_lock');
    if ($lock->tryLock()) {
        // Critical section
        $lock->unlock();
    }
    

5. Performance Tips

  • Cache Keys: Use consistent, deterministic keys (e.g., md5($userId . $request->ip())).
  • Batch Operations: Prefer setMultiple()/getMultiple() over loops.
  • Warm-Up: Pre-populate cache during low-traffic periods (e.g., cron jobs).

6. Debugging

  • Log Adapter Events: Enable Laminas\Cache\Storage\Event\EventInterface listeners:
    $cache->addPlugin(new \Laminas\Cache\Storage\Plugin\Logger([
        'logger' => \Log::channel('cache'),
    ]));
    
  • Check Cache Stats:
    $stats = $this->cache->getMetadata('stats');
    

7. Laravel-Specific Tips

  • Cache Tags in Laravel: Use Cache::tags() for tag-based invalidation (requires Laravel's built-in cache system, but Laminas can integrate via Cache::store()).
  • Cache Events: Listen to cache.hit/cache.miss events in Laravel:
    Cache::extend('laminas', function () {
        return new SimpleCacheDecorator($laminasCache);
    });
    

8. Common Errors & Fixes

Error Cause Solution
Serialization of 'Closure' is not allowed Passing closures to cache. Avoid caching closures; use serialized data.
Cache directory not writable Filesystem permissions. chmod -R 775 storage/framework/cache.
Redis connection failed Misconfigured Redis. Verify host, port, and auth.
APCu not available Extension not installed. pecl install apcu.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony