Download the PHP package coroq/with-cache without Composer
On this page you can find all versions of the php package coroq/with-cache. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package with-cache
coroq/with-cache
A trait for building type-safe caching wrappers.
Requirements
- PHP 8.0+
- PSR-6 cache implementation
Installation
Quick Start
Create a caching decorator class that wraps your original class. When a method is called, the result is cached. Subsequent calls with the same arguments return the cached result without calling the origin.
Benefits
- Separation of concerns - The wrapper class adds caching around the original object. The original class can focus on pure business logic without any knowledge of caching.
- Respects types - The wrapper class implements the same interface as the original, with real methods and real type hints. IDE autocompletion works. Static analyzers like PHPStan understand your code. You can swap between cached and non-cached versions in your DI container.
Usage
Basic Caching
Each method that should be cached calls withCache():
Bypassing Cache
Use withoutCache() to skip caching for specific calls:
Handling Cache Errors
Cache exceptions can be caught per-method:
Custom TTL
By default, cached items have no expiration (live until the cache evicts them). Override getCacheTtl() to control expiration:
TTL can depend on the result:
Custom Cache Key
Override makeCacheKey() to customize key generation:
Note: Arguments must be serializable. Closures, resources, and some anonymous classes cannot be used as arguments for cached methods.
Static Methods
Static methods cannot be cached with this trait. If the original class has static methods, implement them by calling the original directly:
Cache Invalidation
The trait provides two protected methods for cache invalidation:
clearCache()- clears all cached items in the pooldeleteCacheItem(string $methodName, mixed ...$arguments)- deletes a specific cached result
Use these inside your cached class to invalidate stale entries:
Note: clearCache() calls clear() on the underlying cache pool. If you need isolated clearing per service, configure separate cache pools.
License
MIT