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 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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Required Packages:

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

    (Replace filesystem with your preferred adapter like redis, memcached, etc.)

  2. Configure Cache in Laravel: Add cache configuration to config/app.php under cache:

    'cache' => [
        'default' => env('CACHE_DRIVER', 'file'),
        'stores' => [
            'file' => [
                'driver' => 'file',
                'path' => storage_path('framework/cache'),
            ],
            // Add other adapters (e.g., Redis, Memcached)
        ],
    ],
    
  3. First Use Case: Caching Expensive Operations

    use Laminas\Cache\Storage\StorageInterface;
    use Illuminate\Support\Facades\Cache;
    
    // Get cache instance (Laravel's Cache facade wraps Laminas under the hood)
    $cache = Cache::store('file')->getStore();
    
    // Cache a value with TTL (3600 seconds = 1 hour)
    $cache->setItem('expensive_operation_result', $expensiveOperation(), 3600);
    
    // Retrieve cached value
    $result = $cache->getItem('expensive_operation_result');
    

Implementation Patterns

1. Dependency Injection in Laravel

Leverage Laravel's built-in cache system (which uses Laminas under the hood):

// In a service class
public function __construct(
    protected StorageInterface $cache // Injected via Laravel's container
) {}

public function fetchData()
{
    return $this->cache->hasItem('data')
        ? $this->cache->getItem('data')
        : $this->fetchFromDatabase();
}

2. PSR-16 Compliance (SimpleCache)

Wrap Laminas cache for PSR-16 compatibility:

use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;

// Initialize
$laminasCache = Cache::store('redis')->getStore();
$psr16Cache = new SimpleCacheDecorator($laminasCache);

// Use PSR-16 methods
$psr16Cache->set('key', 'value', 3600);
$value = $psr16Cache->get('key');

3. Caching Strategies

  • Output Caching:

    $cacheKey = 'view_' . md5($request->url());
    $content = $cache->getItem($cacheKey);
    if (!$content) {
        $content = view('home')->render();
        $cache->setItem($cacheKey, $content, 300); // 5 minutes
    }
    echo $content;
    
  • Class/Object Caching:

    $cacheKey = 'user_' . $userId;
    $user = $cache->getItem($cacheKey);
    if (!$user) {
        $user = User::find($userId);
        $cache->setItem($cacheKey, $user, 3600);
    }
    

4. Tag-Based Cache Invalidation

Use tags for grouped invalidation (requires adapter support, e.g., Redis):

// Set with tags
$cache->setItem('user_123', $user, 3600, ['users', 'user:123']);

// Invalidate by tag
$cache->removeItemsByTags(['users']);

5. Cache Plugins

Extend functionality with plugins (e.g., serialization for non-serializable data):

use Laminas\Cache\Storage\Plugin\Serializer;

// Add to adapter
$cache->addPlugin(new Serializer());

Gotchas and Tips

Pitfalls

  1. Serialization Issues:

    • Non-serializable objects (e.g., closures, resources) cannot be cached directly.
    • Fix: Use Serializer plugin or implement __serialize()/__unserialize() in your objects.
  2. TTL Misconfiguration:

    • TTL (Time-To-Live) values in seconds (not milliseconds).
    • Fix: Use DateInterval for complex durations:
      $cache->setItem('key', $value, new DateInterval('P1D')); // 1 day
      
  3. Race Conditions:

    • Check-then-Act patterns (e.g., hasItem + setItem) can fail if another process modifies the cache between checks.
    • Fix: Use atomic operations (e.g., addItem for "set if not exists"):
      $cache->addItem('key', $value, 3600); // Only sets if 'key' doesn't exist
      
  4. Adapter-Specific Quirks:

    • Filesystem: Cache files may exceed disk limits. Fix: Set cache_dir to a large partition or use tmpfs.
    • Redis/Memcached: Network latency can slow down operations. Fix: Use local caching (e.g., Memory adapter) for ultra-fast but volatile data.
  5. Laravel-Specific:

    • Laravel’s Cache facade does not expose the full StorageInterface.
    • Fix: Use Cache::store('driver')->getStore() to access Laminas methods.

Debugging Tips

  1. Enable Cache Logging:

    $cache->setOption('logging', true);
    $cache->setOption('log_writer', new \Laminas\Log\Writer\Stream(storage_path('logs/cache.log')));
    
  2. Clear Cache Programmatically:

    $cache->clear(); // Clears all items
    $cache->removeItem('key'); // Removes specific item
    
  3. Benchmark Adapters: Use Laminas’ built-in benchmarks:

    vendor/bin/phpbench run --report=aggregate
    

Extension Points

  1. Custom Adapters: Implement Laminas\Cache\Storage\StorageInterface for new backends (e.g., S3, DynamoDB).

  2. Plugins: Create plugins for:

    • Compression (reduce storage usage).
    • Encryption (secure sensitive data).
    • Event listeners (e.g., log cache hits/misses).
  3. Laravel Integration: Extend Laravel’s CacheManager to support Laminas adapters:

    // config/cache.php
    'stores' => [
        'laminas' => [
            'driver' => 'laminas',
            'adapter' => Laminas\Cache\Storage\Adapter\Redis::class,
            'options' => [
                'host' => 'redis',
                'port' => 6379,
            ],
        ],
    ],
    

Performance Tips

  • Cache Granularity: Cache at the coarsest level possible (e.g., full page vs. partial fragments).
  • TTL Strategy:
    • Short TTL (e.g., 5–30 mins) for volatile data.
    • Long TTL (e.g., 1–24 hours) for static assets.
  • Avoid Over-Caching: Cache only what actually improves performance (measure with microtime()).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport