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).
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).
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());
Where to Look First:
SmartCache\Facades\SmartCache (drop-in replacement for Cache).smart_cache(['key' => $value], $ttl) for quick use.php artisan vendor:publish --tag=smart-cache-config.Transparent Optimization:
SmartCache::remember() for automatic compression/chunking of large payloads (e.g., Eloquent collections, API responses).$largeDataset = SmartCache::remember('analytics_report', 3600, fn() => Analytics::generate());
Stale-While-Revalidate (SWR) Patterns:
$data = SmartCache::swr('external_api', fn() => Http::get('...')->json(), 300, 900);
asyncSwr() with Laravel queues for heavy operations:
$data = SmartCache::asyncSwr('dashboard_stats', fn() => Stats::generate(), 300, 900, 'cache-refresh');
Conditional Caching:
$data = SmartCache::rememberIf('external_api', 3600,
fn() => Http::get('...')->json(),
fn($value) => !empty($value) && isset($value['status'])
);
Dependency Tracking:
SmartCache::dependsOn('user_posts', 'user_profile');
SmartCache::invalidate('user_profile'); // Clears 'user_posts' too
Model Auto-Invalidation:
use SmartCache\Traits\CacheInvalidation;
class User extends Model {
use CacheInvalidation;
public function getCacheKeysToInvalidate(): array {
return ["user_{$this->id}_profile"];
}
}
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.
Closure Serialization in asyncSwr:
asyncSwr() throw InvalidArgumentException (v1.12.0+)."Class@method" strings:
SmartCache::asyncSwr('key', 'App\Services\DataGenerator@generate', 300, 900, 'queue');
Memory Limits with Chunking:
memory_limit.'strategies' => ['chunking' => ['lazy_loading' => true]],
Provider Caching Conflicts:
Class 'SmartCache' not found.php artisan optimize:clear
Binary Data Compression:
'strategies' => ['compression' => ['exclude_patterns' => ['/^image_/']]],
Chunk Corruption:
SmartCache to treat entries as misses.SmartCache::cleanup-chunks CLI command to repair:
php artisan smart-cache:cleanup-chunks
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}"));
Custom Strategies:
SmartCache\Strategies\StrategyInterface to add logic (e.g., custom compression).config/smart-cache.php:
'strategies' => ['custom' => App\Strategies\MyStrategy::class],
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)
],
Adaptive Compression: Dynamically adjust compression levels:
'strategies' => ['compression' => ['mode' => 'adaptive']],
Encryption at Rest: Secure sensitive keys:
'strategies' => ['encryption' => ['enabled' => true, 'keys' => ['secret_*']]],
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());
How can I help you explore Laravel packages today?