PHPackages                             iazaran/smart-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. iazaran/smart-cache

ActiveLibrary[Caching](/categories/caching)

iazaran/smart-cache
===================

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

1.9.2(2mo ago)2057.2k↑29.5%8MITPHPPHP ^8.1CI passing

Since Apr 22Pushed 2mo ago4 watchersCompare

[ Source](https://github.com/iazaran/smart-cache)[ Packagist](https://packagist.org/packages/iazaran/smart-cache)[ Docs](https://github.com/iazaran/smart-cache)[ RSS](/packages/iazaran-smart-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (16)Versions (28)Used By (0)

Laravel SmartCache
==================

[](#laravel-smartcache)

[![Latest Version](https://camo.githubusercontent.com/6769f71bf7fd2e43c7dfc36209590610720a4cfd86c00f02e647b416572fb05a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69617a6172616e2f736d6172742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iazaran/smart-cache)[![Total Downloads](https://camo.githubusercontent.com/9bcba3653766080fcea103e1045be62f38f0e912412c6eeedad666d7d53a139a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69617a6172616e2f736d6172742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iazaran/smart-cache)[![GitHub Stars](https://camo.githubusercontent.com/f3e3e903af5c7c72161dbb7f2a90a15924dfda52e92e0104ef6550e1045ebe1d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f69617a6172616e2f736d6172742d63616368653f7374796c653d666c61742d737175617265)](https://github.com/iazaran/smart-cache)[![License](https://camo.githubusercontent.com/f847a9822c4d17db5b9f70077f3abf42538249b17ba12cdc05db0df6e9eb94a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f69617a6172616e2f736d6172742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iazaran/smart-cache)[![PHP Version](https://camo.githubusercontent.com/428ef520c8529b35c22f9249a49ff88590e3a489b5ed0413d1698d23d0a140a1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f69617a6172616e2f736d6172742d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iazaran/smart-cache)[![Tests](https://camo.githubusercontent.com/53fe6859e8807a83da44838455922cdd06b4e15e3744b95b49f0d6795a68770c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3432352532307061737365642d627269676874677265656e3f7374796c653d666c61742d737175617265)](https://github.com/iazaran/smart-cache/actions)

**Drop-in replacement for Laravel's `Cache` facade** that automatically compresses, chunks, and optimizes cached data — with write deduplication, self-healing recovery, and cost-aware eviction built in.

Implements `Illuminate\Contracts\Cache\Repository` and PSR-16 `SimpleCache`. Your existing code works unchanged.

**PHP 8.1+ · Laravel 8–13 · Redis, File, Database, Memcached, Array**

---

Installation
------------

[](#installation)

```
composer require iazaran/smart-cache
```

That's it. No configuration required — works immediately with your existing cache driver.

Quick Start
-----------

[](#quick-start)

```
use SmartCache\Facades\SmartCache;

// Same API you already know
SmartCache::put('users', $users, 3600);
$users = SmartCache::get('users');

// Remember pattern — with automatic compression & cost tracking
$users = SmartCache::remember('users', 3600, fn() => User::all());

// Helper function
smart_cache(['products' => $products], 3600);
$products = smart_cache('products');
```

Large data is automatically compressed and chunked behind the scenes. No code changes needed.

Why SmartCache?
---------------

[](#why-smartcache)

ProblemWithout SmartCacheWith SmartCacheLarge payloads (100 KB+)Stored as-is, slow readsAuto-compressed &amp; chunkedRedundant writesEvery `put()` hits the storeSkipped when unchanged (write deduplication)Corrupted entriesException crashes the requestAuto-evicted and regenerated (self-healing)Eviction decisionsLRU / randomCost-aware scoring — keeps high-value keysCache stampedeThundering herd on expiryXFetch, jitter, and rate limitingConditional cachingManual `if` around `put()``rememberIf()` — one-linerStale data servingNot availableSWR, stale, refresh-ahead, async queue refreshObservabilityDIY loggingBuilt-in dashboard, metrics, and health checks### How Automatic Optimization Works

[](#how-automatic-optimization-works)

SmartCache selects the best strategy based on your data — zero configuration:

Data ProfileStrategy AppliedEffectArrays with 5 000+ itemsChunkingLower memory, faster accessSerialized data &gt; 50 KBCompressionSignificant size reduction (gzip)API responses &gt; 100 KBChunking + CompressionBest of bothData &lt; 50 KBNoneZero overheadAll thresholds are [configurable](#configuration).

Features
--------

[](#features)

Every feature below is **opt-in** and backward-compatible.

### Multiple Cache Drivers

[](#multiple-cache-drivers)

```
// Each store preserves all SmartCache optimizations
SmartCache::store('redis')->put('key', $value, 3600);
SmartCache::store('memcached')->remember('users', 3600, fn() => User::all());

// Bypass SmartCache when needed
SmartCache::repository('redis')->put('key', $value, 3600);
```

### SWR Patterns (Stale-While-Revalidate)

[](#swr-patterns-stale-while-revalidate)

```
// Serve stale data while refreshing in background
$data = SmartCache::swr('github_repos', fn() => Http::get('...')->json(), 300, 900);

// Extended stale serving (1 h fresh, 24 h stale)
$config = SmartCache::stale('site_config', fn() => Config::fromDatabase(), 3600, 86400);

// Proactive refresh before expiry
$analytics = SmartCache::refreshAhead('daily_analytics', fn() => Analytics::generateReport(), 1800, 300);

// Queue-based background refresh — returns stale immediately
$data = SmartCache::asyncSwr('dashboard_stats', fn() => Stats::generate(), 300, 900, 'cache-refresh');
```

### Stampede Protection

[](#stampede-protection)

```
// XFetch algorithm — probabilistic early refresh
$data = SmartCache::rememberWithStampedeProtection('key', 3600, fn() => expensiveQuery());

// Rate-limited regeneration
SmartCache::throttle('api_call', 10, 60, fn() => expensiveApiCall());

// TTL jitter — prevents thundering herd on expiry
SmartCache::withJitter(0.1)->put('popular_data', $data, 3600);
// Actual TTL: 3240–3960 s (±10 %)
```

### Write Deduplication (Cache DNA)

[](#write-deduplication-cache-dna)

Hashes every value before writing. Identical content → write skipped entirely.

```
SmartCache::put('app_config', Config::all(), 3600);
SmartCache::put('app_config', Config::all(), 3600); // no I/O — data unchanged
```

### Self-Healing Cache

[](#self-healing-cache)

Corrupted entries are auto-evicted and regenerated on next read — zero downtime.

```
$report = SmartCache::remember('report', 3600, fn() => Analytics::generate());
```

### Conditional Caching

[](#conditional-caching)

```
$data = SmartCache::rememberIf('external_api', 3600,
    fn() => Http::get('https://api.example.com/data')->json(),
    fn($value) => !empty($value) && isset($value['status'])
);
```

### Cost-Aware Eviction

[](#cost-aware-eviction)

GreedyDual-Size–inspired scoring: `score = (cost × ln(1 + access_count) × decay) / size`

```
SmartCache::remember('analytics', 3600, fn() => AnalyticsService::generateReport());
SmartCache::getCacheValueReport();       // all entries ranked by value
SmartCache::suggestEvictions(5);         // lowest-value entries to remove
```

### Circuit Breaker &amp; Fallback

[](#circuit-breaker--fallback)

```
$data = SmartCache::withFallback(
    fn() => SmartCache::get('key'),
    fn() => $this->fallbackSource()
);
```

### In-Request Memoization

[](#in-request-memoization)

```
$memo = SmartCache::memo();
$users = $memo->remember('users', 3600, fn() => User::all());
$users = $memo->get('users'); // instant — served from memory
```

### Atomic Locks

[](#atomic-locks)

```
SmartCache::lock('expensive_operation', 10)->get(function () {
    return regenerateExpensiveData();
});
```

### Namespacing

[](#namespacing)

```
SmartCache::namespace('api_v2')->put('users', $users, 3600);
SmartCache::flushNamespace('api_v2');
```

### Cache Invalidation

[](#cache-invalidation)

```
// Pattern-based
SmartCache::flushPatterns(['user_*', 'api_v2_*', '/product_\d+/']);

// Dependency tracking
SmartCache::dependsOn('user_posts', 'user_profile');
SmartCache::invalidate('user_profile'); // also clears user_posts

// Tag-based
SmartCache::tags(['users'])->put('user_1', $user, 3600);
SmartCache::flushTags(['users']);
```

### Model Auto-Invalidation

[](#model-auto-invalidation)

```
use SmartCache\Traits\CacheInvalidation;

class User extends Model
{
    use CacheInvalidation;

    public function getCacheKeysToInvalidate(): array
    {
        return ["user_{$this->id}_profile", "user_{$this->id}_posts", 'users_list_*'];
    }
}
```

### Encryption at Rest

[](#encryption-at-rest)

```
// config/smart-cache.php → strategies.encryption
'encryption' => [
    'enabled' => true,
    'keys' => ['user_token_abc123'],          // exact cache-key match
    'patterns' => ['/^user_token_/', '/^payment_/'],  // regex match
],
```

### Adaptive Compression

[](#adaptive-compression)

```
config(['smart-cache.strategies.compression.mode' => 'adaptive']);
// Hot data → fast compression (level 3–4), cold data → high compression (level 7–9)
```

### Lazy Loading

[](#lazy-loading)

```
config(['smart-cache.strategies.chunking.lazy_loading' => true]);
$dataset = SmartCache::get('100k_records'); // LazyChunkedCollection
foreach ($dataset as $record) { /* max 3 chunks in memory */ }
```

### Batch Operations

[](#batch-operations)

```
$values = SmartCache::many(['key1', 'key2', 'key3']);
SmartCache::putMany(['key1' => $a, 'key2' => $b], 3600);
SmartCache::deleteMultiple(['key1', 'key2', 'key3']);
```

### Cache Events

[](#cache-events)

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

### Monitoring &amp; Dashboard

[](#monitoring--dashboard)

```
SmartCache::getPerformanceMetrics(); // hit_ratio, compression_savings, timing
SmartCache::analyzePerformance();    // health score + recommendations
```

```
// Enable web dashboard
'dashboard' => ['enabled' => true, 'prefix' => 'smart-cache', 'middleware' => ['web', 'auth']],
// GET /smart-cache/dashboard | /smart-cache/stats | /smart-cache/health
```

```
php artisan smart-cache:status
php artisan smart-cache:clear
php artisan smart-cache:warm --warmer=products --warmer=categories
php artisan smart-cache:cleanup-chunks
```

Configuration
-------------

[](#configuration)

Publish the config file (optional — sensible defaults are applied automatically):

```
php artisan vendor:publish --tag=smart-cache-config
```

```
// config/smart-cache.php (excerpt)
return [
    'thresholds' => [
        'compression' => 1024 * 50,  // 50 KB
        'chunking'    => 1024 * 100, // 100 KB
    ],
    'strategies' => [
        'compression' => ['enabled' => true, 'mode' => 'fixed', 'level' => 6],
        'chunking'    => ['enabled' => true, 'chunk_size' => 1000],
        'encryption'  => ['enabled' => false, 'keys' => []],
    ],
    'monitoring'      => ['enabled' => true, 'metrics_ttl' => 3600],
    'circuit_breaker' => ['enabled' => false, 'failure_threshold' => 5, 'recovery_timeout' => 30],
    'rate_limiter'    => ['enabled' => true, 'window' => 60, 'max_attempts' => 10],
    'jitter'          => ['enabled' => false, 'percentage' => 0.1],
    'deduplication'   => ['enabled' => true],   // Write deduplication (Cache DNA)
    'self_healing'    => ['enabled' => true],   // Auto-evict corrupted entries
    'dashboard'       => ['enabled' => false, 'prefix' => 'smart-cache', 'middleware' => ['web']],
    'warmers'         => [],                    // Cache warmer classes for smart-cache:warm
];
```

Migration from Laravel Cache
----------------------------

[](#migration-from-laravel-cache)

Change one import — everything else stays the same:

```
- use Illuminate\Support\Facades\Cache;
+ use SmartCache\Facades\SmartCache;

SmartCache::put('users', $users, 3600);
$users = SmartCache::get('users');
```

Documentation
-------------

[](#documentation)

[Full documentation →](https://iazaran.github.io/smart-cache/) — Installation, API reference, SWR patterns, and more.

Testing
-------

[](#testing)

```
composer test            # 425 tests, 1 780+ assertions
composer test-coverage   # with code coverage
```

See [TESTING.md](TESTING.md) for details.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md).

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

Links
-----

[](#links)

- [Packagist](https://packagist.org/packages/iazaran/smart-cache)
- [GitHub Issues](https://github.com/iazaran/smart-cache/issues)
- [Documentation](https://iazaran.github.io/smart-cache/)

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance88

Actively maintained with recent releases

Popularity42

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~13 days

Total

25

Last Release

61d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10566709?v=4)[Ismael Azaran](/maintainers/iazaran)[@iazaran](https://github.com/iazaran)

---

Top Contributors

[![iazaran](https://avatars.githubusercontent.com/u/10566709?v=4)](https://github.com/iazaran "iazaran (165 commits)")[![sc85](https://avatars.githubusercontent.com/u/4824890?v=4)](https://github.com/sc85 "sc85 (1 commits)")

---

Tags

cachecache-managementcachingcomposer-packagedata-compressionlaravellaravel-packagelaravel-packagesoptimizationperformancephpredislaravel-packagepsr-16redis-cachefile cacheswrstale-while-revalidatedata-compressionlaravel performancecache managementlaravel cache driverlaravel optimizationsmart-cachesmart cache laravellaravel cachingcache optimizationcache chunkingcache serializationcache strategiesphp cachingcache stampede preventioncost-aware evictionself-healing cachewrite deduplicationlaravel cache replacement

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/iazaran-smart-cache/health.svg)

```
[![Health](https://phpackages.com/badges/iazaran-smart-cache/health.svg)](https://phpackages.com/packages/iazaran-smart-cache)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[genealabs/laravel-model-caching

Automatic caching for Eloquent models.

2.4k4.8M26](/packages/genealabs-laravel-model-caching)[mikebronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k127.1k1](/packages/mikebronner-laravel-model-caching)[propaganistas/laravel-disposable-email

Disposable email validator

5762.6M6](/packages/propaganistas-laravel-disposable-email)[laragear/cache-query

Remember your query results using only one method. Yes, only one.

272122.8k](/packages/laragear-cache-query)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
