gregwar/cache
gregwar/cache is a lightweight PHP caching library with a simple API for caching values and function results. Supports multiple backends (filesystem, APC/APCu, memcache), TTL expiration, cache namespaces/prefixes, and easy integration into existing apps.
Installation
composer require gregwar/cache
No additional configuration is needed—just autoload the package.
Basic Usage
use Gregwar\Cache\Cache;
$cache = new Cache('/path/to/cache/directory');
$cache->set('key', 'value', 3600); // Cache for 1 hour
$value = $cache->get('key');
First Use Case Cache database query results to reduce load:
$users = $cache->remember('expensive_query', 60, function () {
return User::all()->toArray();
});
Cache Warming Preload critical data during low-traffic periods:
$cache->set('featured_products', Product::featured()->get(), 300);
Conditional Caching
Use remember() for dynamic data with fallback logic:
$data = $cache->remember('user_'.$userId, 300, function () use ($userId) {
return User::find($userId)->load('posts');
});
Cache Invalidation Clear stale data on updates:
// After updating a user
$cache->forget('user_'.$userId);
$cache->forget('user_'.$userId.'_posts');
Tag-Based Invalidation Group related cache keys (requires custom implementation):
$cache->set('tag:products:123', $product, 3600);
// Later: Clear all 'tag:products:*' keys
Integration with Laravel Bind the package to Laravel’s cache manager:
Cache::extend('gregwar', function ($app) {
return new Gregwar\Cache\Cache(storage_path('framework/cache/gregwar'));
});
Then use Cache::driver('gregwar')->get('key').
Directory Permissions Ensure the cache directory is writable by the web server:
chmod -R 775 /path/to/cache
Symptom: Silent failures or PermissionDeniedException.
Key Collisions
Avoid using special characters (e.g., :, /) in keys unless URL-encoded.
Fix: Sanitize keys:
$safeKey = str_replace(['/', ':'], '_', $userId);
Memory vs. Disk
Large cached data (e.g., serialized objects) may bloat storage.
Tip: Use serialize()/unserialize() for complex objects:
$cache->set('user_data', serialize($user));
$user = unserialize($cache->get('user_data'));
TTL Granularity
Seconds are the smallest unit. For sub-second precision, use 0 (no expiry) and manually invalidate.
Race Conditions
remember() is not atomic. For critical sections, use locks:
$cache->lock('update_key', 5, function () {
// Critical update logic
});
/path/to/cache/ for corrupted or unexpected files.$cache = new Cache($dir, [
'logger' => new \Monolog\Logger('cache', [$handler]),
]);
Custom Storage
Override Cache::getStorage() to use S3, Redis, etc.:
class CustomCache extends Cache {
protected function getStorage() {
return new \League\Flysystem\Filesystem(...);
}
}
Event Hooks
Trigger events on set/get/forget by extending the class and overriding methods.
Compression Enable GZIP for large cache files:
$cache->set('large_data', gzcompress($data), 3600);
$data = gzuncompress($cache->get('large_data'));
Fallback Cache Implement a multi-layer cache (e.g., Redis + Filesystem):
$fallback = new Cache($dir);
$primary = Cache::store('redis');
return $primary->get('key') ?? $fallback->get('key');
How can I help you explore Laravel packages today?