thecodingmachine/cache-utils
Small set of PHP cache helpers by TheCodingMachine: adapters and utilities around PSR-6/PSR-16 caches, including cache wrappers and simple tooling to standardize access, reduce boilerplate, and ease integration in frameworks and libraries.
Installation
composer require thecodingmachine/cache-utils
No Laravel-specific configuration is required—this package is framework-agnostic.
Basic Usage
Inject the CacheUtils service into your Laravel service container:
use TheCodingMachine\Cache\CacheUtils;
use Psr\Cache\CacheItemPoolInterface;
// In a service provider (e.g., AppServiceProvider)
$this->app->bind(CacheUtils::class, function ($app) {
return new CacheUtils($app->make(CacheItemPoolInterface::class));
});
First Use Case: Safe Cache Retrieval
use TheCodingMachine\Cache\CacheUtils;
class MyService {
private $cacheUtils;
public function __construct(CacheUtils $cacheUtils) {
$this->cacheUtils = $cacheUtils;
}
public function getCachedData(string $key, callable $callback) {
return $this->cacheUtils->get($key, $callback, 3600); // Cache for 1 hour
}
}
Use CacheUtils to generate consistent, namespaced keys:
$key = $cacheUtils->getKey('my_namespace', 'dynamic_key', ['param1', 'param2']);
// Output: "my_namespace:dynamic_key:param1:param2"
Laravel Integration Tip: Combine with Laravel’s cache tags for invalidation:
$key = $cacheUtils->getKey('laravel:user', $userId);
Cache::tags(['user:' . $userId])->put($key, $data, 3600);
Atomic get/set with fallback:
$data = $cacheUtils->get('expensive_data', function () {
return $this->fetchExpensiveData();
}, 3600);
Conditional updates:
$cacheUtils->updateIf('user:profile', function ($item) {
$item->set($this->updateProfileData());
}, 3600, function ($item) {
return $item->isHit();
});
Tag-based invalidation (Laravel-specific):
$cacheUtils->invalidateTag('user:profile'); // Clears all keys tagged with "user:profile"
Wildcard invalidation:
$cacheUtils->invalidate('user:*'); // Clears all user-related keys
Wrap Laravel’s cache in CacheUtils for consistency:
$cacheUtils = new CacheUtils(Cache::store('array')); // Or any PSR-16 adapter
Use with Laravel’s Cache::remember alternative:
$data = $cacheUtils->remember('key', 3600, function () {
return Model::query()->first();
});
$key = $cacheUtils->getKey('laravel:', 'my_key');
file driver).Cache::store('redis') or Cache::store('database') for tag support.Cache::store('array')->setLogger(new \Monolog\Logger('cache'));
CacheUtils to add namespaces:
$cacheUtils = new CacheUtils($cachePool, 'my_app:');
CacheUtils::addListener().Cache::tags() is not PSR-16 compliant. Use CacheUtils for cross-adapter consistency.Cache handles this, but raw PSR-16 may not).CacheUtils::batchGet() to reduce round trips:
$keys = ['key1', 'key2'];
$results = $cacheUtils->batchGet($keys);
How can I help you explore Laravel packages today?