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

Smart Cache Laravel Package

iazaran/smart-cache

Drop-in replacement for Laravel’s Cache facade that automatically compresses and chunks large values, deduplicates unchanged writes, self-heals corrupted entries, and performs cost-aware eviction. Works with existing code (PHP 8.1+, Laravel 8–13).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add via Composer:

    composer require iazaran/smart-cache
    

    No further setup required—works immediately with existing Laravel cache drivers (Redis, File, Database, Memcached, Array).

  2. First Use Case: Replace Laravel’s Cache facade with SmartCache:

    use SmartCache\Facades\SmartCache;
    
    // Basic caching (unchanged API)
    SmartCache::put('users', $users, 3600);
    $users = SmartCache::get('users');
    
    // Automatic compression/chunking with `remember`
    $users = SmartCache::remember('users', 3600, fn() => User::all());
    
  3. Where to Look First:

    • Facade: SmartCache\Facades\SmartCache (drop-in replacement for Cache).
    • Helper Function: smart_cache(['key' => $value], $ttl) for quick use.
    • Configuration: Publish defaults with php artisan vendor:publish --tag=smart-cache-config.

Implementation Patterns

Core Workflows

  1. Transparent Optimization:

    • Use SmartCache::remember() for automatic compression/chunking of large payloads (e.g., Eloquent collections, API responses).
    • Example:
      $largeDataset = SmartCache::remember('analytics_report', 3600, fn() => Analytics::generate());
      
  2. Stale-While-Revalidate (SWR) Patterns:

    • Serve stale data while refreshing in the background:
      $data = SmartCache::swr('external_api', fn() => Http::get('...')->json(), 300, 900);
      
    • Async Refresh: Use asyncSwr() with Laravel queues for heavy operations:
      $data = SmartCache::asyncSwr('dashboard_stats', fn() => Stats::generate(), 300, 900, 'cache-refresh');
      
  3. Conditional Caching:

    • Cache only if data meets criteria:
      $data = SmartCache::rememberIf('external_api', 3600,
          fn() => Http::get('...')->json(),
          fn($value) => !empty($value) && isset($value['status'])
      );
      
  4. Dependency Tracking:

    • Invalidate related caches when a key changes:
      SmartCache::dependsOn('user_posts', 'user_profile');
      SmartCache::invalidate('user_profile'); // Clears 'user_posts' too
      
  5. Model Auto-Invalidation:

    • Extend Eloquent models to auto-flush caches:
      use SmartCache\Traits\CacheInvalidation;
      
      class User extends Model {
          use CacheInvalidation;
      
          public function getCacheKeysToInvalidate(): array {
              return ["user_{$this->id}_profile"];
          }
      }
      

Integration Tips

  • Multi-Driver Support: Use named stores for isolation:

    SmartCache::store('redis')->put('key', $value, 3600);
    SmartCache::store('memcached')->remember('users', 3600, fn() => User::all());
    
  • Batch Operations: Optimize bulk cache updates:

    SmartCache::putMany(['key1' => $a, 'key2' => $b], 3600);
    SmartCache::deleteMultiple(['key1', 'key2']);
    
  • Namespacing: Organize caches by feature:

    SmartCache::namespace('api_v2')->put('users', $users, 3600);
    SmartCache::flushNamespace('api_v2');
    
  • Monitoring: Add dashboard middleware and track metrics:

    // config/smart-cache.php
    'dashboard' => ['enabled' => true, 'middleware' => ['web', 'auth']],
    

    Access at /smart-cache/dashboard.


Gotchas and Tips

Pitfalls

  1. Closure Serialization in asyncSwr:

    • Issue: Closures in asyncSwr() throw InvalidArgumentException (v1.12.0+).
    • Fix: Use serializable invokables or "Class@method" strings:
      SmartCache::asyncSwr('key', 'App\Services\DataGenerator@generate', 300, 900, 'queue');
      
  2. Memory Limits with Chunking:

    • Issue: Large datasets (>100K items) may exceed memory_limit.
    • Fix: Enable lazy loading in config:
      'strategies' => ['chunking' => ['lazy_loading' => true]],
      
  3. Provider Caching Conflicts:

    • Issue: Laravel caches service providers/aliases, causing Class 'SmartCache' not found.
    • Fix: Clear optimized classes:
      php artisan optimize:clear
      
  4. Binary Data Compression:

    • Issue: Compressing already-compressed data (e.g., images) wastes CPU.
    • Fix: Exclude keys via config:
      'strategies' => ['compression' => ['exclude_patterns' => ['/^image_/']]],
      
  5. Chunk Corruption:

    • Issue: Missing chunks cause SmartCache to treat entries as misses.
    • Fix: Use SmartCache::cleanup-chunks CLI command to repair:
      php artisan smart-cache:cleanup-chunks
      

Debugging Tips

  • Audit Cache Health: Run the audit command to detect issues:

    php artisan smart-cache:audit --driver=redis
    

    Output includes missing keys, orphan chunks, and eviction suggestions.

  • Benchmark Performance: Compare optimization strategies:

    php artisan smart-cache:bench --profile=api-json --driver=redis
    
  • Enable Events for Logging: Track hits/misses in real-time:

    config(['smart-cache.events.enabled' => true]);
    Event::listen(CacheHit::class, fn($e) => Log::info("Hit: {$e->key}"));
    

Extension Points

  1. Custom Strategies:

    • Extend SmartCache\Strategies\StrategyInterface to add logic (e.g., custom compression).
    • Register in config/smart-cache.php:
      'strategies' => ['custom' => App\Strategies\MyStrategy::class],
      
  2. Override Default Thresholds: Adjust compression/chunking triggers:

    'thresholds' => [
        'compression' => 1024 * 25,  // 25 KB (lower than default 50 KB)
        'chunking'    => 1024 * 50,  // 50 KB (lower than default 100 KB)
    ],
    
  3. Adaptive Compression: Dynamically adjust compression levels:

    'strategies' => ['compression' => ['mode' => 'adaptive']],
    
  4. Encryption at Rest: Secure sensitive keys:

    'strategies' => ['encryption' => ['enabled' => true, 'keys' => ['secret_*']]],
    

Pro Tips

  • Use SmartCache::repository() for raw store access when needed:

    SmartCache::repository('redis')->put('key', $value, 3600);
    
  • Leverage SmartCache::memo() for in-request memoization:

    $memo = SmartCache::memo();
    $users = $memo->remember('users', 3600, fn() => User::all());
    
  • Stampede Protection: Mitigate cache expiry thundering herds:

    $data = SmartCache::rememberWithStampedeProtection('key', 3600, fn() => expensiveQuery());
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky