Download the PHP package iazaran/smart-cache without Composer
On this page you can find all versions of the php package iazaran/smart-cache. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download iazaran/smart-cache
More information about iazaran/smart-cache
Files in iazaran/smart-cache
Package smart-cache
Short Description 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.
License MIT
Homepage https://github.com/iazaran/smart-cache
Rated 5.00 based on 1 reviews
Informations about the package smart-cache
Laravel SmartCache
A Laravel cache optimizer for large payloads. SmartCache wraps Laravel's familiar cache API with automatic compression, driver-safe chunking, write deduplication, self-healing recovery, and operational diagnostics.
SmartCache implements Illuminate\Contracts\Cache\Repository, which extends the PSR-16 interface. Most Laravel cache calls migrate with an import change; the cache-clearing semantics are intentionally explicit for SmartCache 1.x.
PHP 8.1–8.5 · Laravel 8–13 · Redis, File, Database, Memcached, Array
Installation
Recommended: enable ext-zlib to use gzip compression. JSON support is built into PHP 8+.
No configuration is required to start. SmartCache uses your existing Laravel cache driver and ships with documented defaults.
Compatibility and support
SmartCache tests Laravel 8–13 and PHP 8.1–8.5. Compatibility with an older framework or PHP release does not extend that dependency's upstream security lifetime. For new and enterprise deployments, use a currently supported PHP release and a Laravel version inside the official Laravel support window.
Quick Start
Large values are optimized behind the same familiar API. Adoption can be gradual: change the facade import only where SmartCache is useful.
Why SmartCache?
| Problem | Without SmartCache | With SmartCache |
|---|---|---|
| Large payloads | Stored as one raw value | Auto-compressed or split into driver-safe chunks |
| Driver size limits | Application-managed splitting | Transparent chunking and key-preserving restore |
| Cross-driver invalidation | Driver-specific tags or custom indexes | Tags, dependencies, patterns, and model hooks |
| Redundant writes | Every put() hits the store |
Skipped when unchanged (write deduplication) |
| Corrupted entries | Exception crashes the request | Auto-evicted and regenerated, including broken chunk sets |
| Eviction decisions | LRU / random | Cost-aware scoring — keeps high-value keys |
| Observability | DIY logging | Built-in dashboard, metrics, and health checks |
How Automatic Optimization Works
SmartCache selects the best enabled strategy based on your data; the defaults work without publishing configuration:
| Data Profile | Strategy Applied | Effect |
|---|---|---|
| Large arrays or collections meeting the chunk threshold | Chunking | Driver-safe splitting with key preservation |
| Compressible serialized data above 50 KB | Compression | Reduced stored size with gzip |
| Data below the configured thresholds | No size strategy | Value is stored without compression or chunking |
All thresholds are configurable. Monitoring, managed-key tracking, cost metadata, and write deduplication can still add small metadata or CPU costs even when no size strategy is selected; benchmark your real payloads and driver before production rollout.
When to use SmartCache
- Large Eloquent results, reports, dashboards, or API payloads put pressure on Redis, Memcached, database, or file cache storage.
- You need consistent tag or dependency invalidation across drivers.
- You want cache diagnostics, corruption recovery, and measurable optimization behavior without building a parallel cache layer.
When not to use SmartCache
- Most values are already small and the native Laravel cache meets your latency and operational needs.
- Payloads are already compressed or encrypted and will not benefit from gzip.
- You cannot budget the extra metadata keys used for tracking, deduplication, metrics, tags, dependencies, or chunks.
Production Safety for Large Data
SmartCache is built for the painful cases that appear after an application grows: large Eloquent result sets, API payloads, reports, dashboards, and Redis/Memcached entries that get too big to manage safely.
- Data shape is preserved. Chunked payloads keep associative keys and sparse numeric keys intact, so ID-keyed arrays do not come back reindexed.
- Partial chunk loss is recoverable. If a chunk is missing or corrupted, SmartCache treats the entry as a cache miss, evicts the broken metadata, and lets
remember()regenerate a clean value. - Null remains a valid cached value. Stored
nullis distinguished from a miss, preserving Laravel cache semantics while still enabling self-healing. - Raw repository access is still available. Use
SmartCache::repository()when a package or one-off operation needs the underlying Laravel cache store directly.
Features
Compression, chunking, monitoring, cost tracking, write deduplication, and self-healing have documented enabled defaults. Advanced behavior such as encryption, serialization, TTL jitter, the circuit breaker, cache events, and the dashboard remains opt-in.
Multiple Cache Drivers
SWR Patterns (Stale-While-Revalidate)
How refresh execution works.
swr(),stale()andrefreshAhead()execute a due refresh callback synchronously in the current PHP process before the method returns the stale value. UseasyncSwr()with a Laravel queue worker when the caller must not wait for regeneration.asyncSwr()does not acceptClosurecallbacks — pass either a serializable invokable class or a"Class@method"string. Closures throwInvalidArgumentExceptionsince v1.12.0 so the failure is loud at dispatch time instead of inside the queue serializer.Single-flight refresh (opt-in, v1.12.0+). Set
smart-cache.swr.single_flight = trueto wrap the synchronous refresh in an opportunistic non-blocking lock keyed on_sc_swr_refresh:{key}. When the cache store implementsLockProvider(redis, memcached, database, dynamodb, file) only one worker regenerates a stale entry; concurrent workers keep serving stale and return immediately. Defaultfalsepreserves the historical "every worker refreshes" behaviour.
Stampede Protection
Single-flight regeneration (v1.15.0+). When a hot key is missing — after a deploy, a flush, or an invalidation —
remember()lets every concurrent request run the callback at once.rememberWithLock()runs it under an atomic lock instead: one process regenerates, the others wait (10 s by default) and then read the stored value. Cache hits never touch the lock. If the store has no lock support (LockProvider) or the wait times out, the callback runs anyway, so the method never fails whereremember()would succeed. On the database cache driver, locks need thecache_lockstable thatphp artisan cache:tablecreates. Tune both limits per call:rememberWithLock($key, $ttl, $callback, lockSeconds: 30, waitSeconds: 5).
Write Deduplication (Cache DNA)
Hashes every value before writing. When the content is unchanged and the cached entry already outlives the TTL being requested, the value rewrite is skipped.
A write that would extend the expiry is never skipped: deduplication must not shorten an entry's lifetime.
Self-Healing Cache
Corrupted entries are auto-evicted instead of being returned. With remember()-style reads, the callback can regenerate the value on the next read. This includes missing chunks from large chunked payloads.
Conditional Caching
Cost-Aware Eviction
GreedyDual-Size–inspired scoring: score = (cost × ln(1 + access_count) × decay) / size
Circuit Breaker & Fallback
In-Request Memoization
Atomic Locks
Namespacing
Cache Invalidation
Use flushTags() to invalidate by tag; flush() clears the entire store. By default, tags set with tags() stay active until a write uses them, so after a tagged get() that misses they also tag the next write, whatever its key. That only causes extra invalidation. New applications can set smart-cache.tags.scoped = true (v1.15.0+). Then, after a tagged lookup, the tags only apply to a later write of a key looked up while they were pending. The "read, then write on a miss" pattern stays tagged, and unrelated writes are not. In that mode, compute values before calling tags(), or use tags()->remember().
Model Auto-Invalidation
Model invalidation is deferred until the current database transaction commits by default (smart-cache.model_invalidation.after_commit = true). This prevents another request from re-caching pre-commit data between an Eloquent event and the final commit. Set the flag to false if you need the historical immediate behavior.
Eloquent events do not fire for saveQuietly(), query-builder update() / delete(), upsert(), mass insert(), or raw SQL. For those paths, call flushCacheTags() or SmartCache::flushTags() explicitly.
Choosing Cache Tags
Tags should describe the data used to build a response, not the controller that built it. Start with the tables or models read by the endpoint: list endpoints usually use coarse tags such as products, while item endpoints can add instance tags such as product_123. Over-tagging causes extra refreshes; under-tagging leaves stale data behind. For hard-to-map endpoints, enable Laravel's query log in a test and compare the tables read during response generation with the tags declared for that cache entry.
Encryption at Rest
Keys and patterns match with or without the active namespace. Matching values are always encrypted, whatever their size: encryption takes precedence over compression and chunking, so a large encrypted value is stored as a single entry.
Adaptive Compression
Lazy Loading
Batch Operations
Cache Events
Monitoring & Dashboard
Protect these routes. The shipped default is
['web'], which provides session and CSRF handling but no authentication. The endpoints expose your managed cache key list, optimization statistics, and internal metrics — cache keys routinely embed user, tenant, or record identifiers. Add an authentication and authorization middleware (['web', 'auth'],['web', 'auth', 'can:viewSmartCache'], or your own gate) before enabling the dashboard outside local development. It is disabled by default.
Cache Audit & Benchmarks
Use the audit command before production changes or after a cache incident:
It reports managed keys, missing tracked keys, broken chunked entries, orphan chunks, large unoptimized values, and cost-aware eviction suggestions without mutating the cache.
Use the benchmark command to measure your own driver and payload behavior:
A generated Redis report is included at docs/benchmark-report-redis.json. On the included PHP 8.4 / Laravel 13 / Redis run, the api-json profile compressed from 323,811 bytes to 7,829 bytes (97.58% smaller). Each profile includes a goal, success_metric, goal_passed, and result_summary field so compression is judged by byte reduction, chunking is judged by driver-safe splitting and key preservation, and small payloads are judged by avoiding unnecessary optimization.
Operational Footprint
SmartCache stores internal metadata in the selected cache store. Depending on the enabled features, this can include _sc_managed_keys, _sc_dna:{key}, _sc_meta:{key}, _sc_chunk_*, _sc_tag_*, _sc_dependencies, _sc_cost_metadata, and _sc_performance_metrics. Use a dedicated cache store or Laravel cache prefix when applications share infrastructure, set managed_keys.max_tracked for high-cardinality workloads, and run smart-cache:audit before and after production changes.
Best Practices & Troubleshooting
- Binary Data: Already-compressed payloads such as images, video, or encrypted data gain nothing from gzip. Write those keys through
SmartCache::repository(), which bypasses SmartCache optimization. - Memory Limits with Chunking: Large multi-megabyte datasets automatically trigger the 'chunking' strategy. For arrays over 100,000 items, verify
memory_limitinphp.inior enablelazy_loadingvia config to avoid server crashes. - Provider Not Found: Laravel aggressively caches service providers and aliases. Always run
php artisan optimize:clearafter upgrading or installing this package if encountering "Class 'SmartCache' not found". - IDE Autocomplete: Modern IDEs (PhpStorm, VSCode) completely resolve
SmartCache::magical methods automatically via our included Facade PHPDocs without needingide-helpergenerated files.
Configuration
Publish the config file (optional — sensible defaults are applied automatically):
Laravel Octane / Long-Running Workers
SmartCache is registered as a singleton, which means per-request state (active tags, namespaces, in-memory metric buffers) would normally leak between requests on Laravel Octane, Swoole, FrankenPHP or RoadRunner. Since v1.12.0 the service provider's terminating() hook calls SmartCache::reset() and OrphanChunkCleanupService::flush() at the end of every request, so there is nothing extra to configure. If you embed SmartCache in your own long-running runtime, call app(\SmartCache\Contracts\SmartCache::class)->reset() between iterations.
Cache Clearing Semantics
SmartCache 1.x preserves its historical managed-only behavior for clear(). Prefer the explicit method in new code:
This is the one intentional behavioral difference to consider when using SmartCache through the PSR-16 interface, where clear() normally means clearing the entire cache pool. The existing behavior remains unchanged in 1.x for backward compatibility.
clearManaged() is available on the facade and concrete SmartCache class. It is intentionally not added to SmartCache\Contracts\SmartCache in the 1.x line, so existing third-party implementations of that contract do not break.
Migration from Laravel Cache
Change one import for the cache operations you want SmartCache to optimize:
Review calls to clear() during migration and choose clearManaged() or flush() explicitly. For incremental adoption, keep Laravel's Cache facade alongside SmartCache and migrate only large or operationally sensitive keys.
Documentation
Full documentation → — Installation, API reference, SWR patterns, and more.
Testing
See TESTING.md for details.
Contributing
Please see CONTRIBUTING.md.
License
MIT — see LICENSE.
Links
All versions of smart-cache with dependencies
illuminate/support Version ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0
illuminate/cache Version ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0
illuminate/console Version ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0
illuminate/contracts Version ^8.0||^9.0||^10.0||^11.0||^12.0||^13.0