PHP code example of iazaran / smart-cache

1. Go to this page and download the library: Download iazaran/smart-cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

iazaran / smart-cache example snippets


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');

// 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);

// Due refreshes run synchronously before this method returns stale data
$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 — use a serializable invokable class
$data = SmartCache::asyncSwr('dashboard_stats', RefreshDashboardStats::class, 300, 900, 'cache-refresh');

// Single-flight regeneration — on a miss, only one process runs the callback
$report = SmartCache::rememberWithLock('daily_report', 3600, fn() => Report::build());

// 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 %)

// Explicit per-call jitter — applies regardless of the global jitter.enabled flag
SmartCache::putWithJitter('popular_data', $data, 3600, 0.2);
SmartCache::rememberWithJitter('report', 3600, 0.1, fn() => Analytics::generate());

SmartCache::put('app_config', Config::all(), 3600);

// Same content, and the stored entry already covers this window → rewrite skipped
SmartCache::put('app_config', Config::all(), 60);

// Same content, but this asks the entry to live longer → written, so the TTL is honoured
SmartCache::put('app_config', Config::all(), 7200);

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

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

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

// With the circuit breaker enabled (circuit_breaker.enabled or withCircuitBreaker()),
// a failing or open circuit returns the fallback; a Closure fallback is called.
$data = SmartCache::withFallback(
    fn() => SmartCache::get('key'),
    fn() => $this->fallbackSource()
);

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

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

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

// 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']);

use SmartCache\Traits\CacheInvalidation;

class User extends Model
{
    use CacheInvalidation;

    protected function cacheInvalidation(): array
    {
        return [
            'keys' => ['user_{id}_profile', 'user_{id}_posts'],
            'tags' => ['users', 'user_{id}', 'team_{team_id}'],
            'patterns' => ['users_list_*'],
            'dependencies' => ['team_{team_id}_summary'],
        ];
    }
}

// Event-blind writes can flush explicitly:
User::where('status', 'inactive')->update(['archived' => true]);
User::flushCacheTags(['users']);

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

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

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

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

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}"));
Event::listen(TagFlushed::class, fn($e) => Log::notice("Flushed {$e->tag}", [
    'keys' => $e->keyCount,
    'source' => $e->source, // manual, model, or model_helper
]));

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 | /smart-cache/statistics | /smart-cache/health | /smart-cache/keys | /smart-cache/commands

// 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,
        'shared'            => false, // v1.12.0: share breaker state across workers via the cache
        'shared_ttl'        => 300,   // v1.12.0: TTL for the shared state key
    ],
    '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
    'swr'             => ['single_flight' => false], // v1.12.0: opt-in single-flight refresh
    'managed_keys'    => ['max_tracked' => 0],       // v1.12.0: 0 = unlimited (default)
    'metadata_lock'   => ['enabled' => true, 'ttl' => 5, 'wait' => 1],
    'model_invalidation' => ['after_commit' => true],
    'tags'            => ['scoped' => false],        // v1.15.0: opt-in scoped tags (recommended for new apps)
    'dashboard'       => ['enabled' => false, 'prefix' => 'smart-cache', 'middleware' => ['web']],
    'warmers'         => [],                    // Cache warmer classes for smart-cache:warm
];

SmartCache::clearManaged(); // Remove SmartCache-tracked entries only
SmartCache::flush();        // Flush the entire underlying cache store

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

SmartCache::put('users', $users, 3600);
$users = SmartCache::get('users');
bash
php artisan smart-cache:status
php artisan smart-cache:audit --driver=redis
php artisan smart-cache:bench --driver=redis --iterations=5
php artisan smart-cache:clear
php artisan smart-cache:warm --warmer=products --warmer=categories
php artisan smart-cache:cleanup-chunks
bash
php artisan smart-cache:audit
php artisan smart-cache:audit --format=json
php artisan smart-cache:audit --driver=redis --limit=50
bash
php artisan smart-cache:bench
php artisan smart-cache:bench --profile=api-json --driver=redis --iterations=10
php artisan smart-cache:bench --format=json --output=storage/smart-cache-bench.json
bash
php artisan vendor:publish --tag=smart-cache-config