Installation Add the package via Composer:
composer require zetacomponents/cache
Register the service provider in config/app.php:
'providers' => [
// ...
ZetaComponents\Cache\Cache::class,
],
Basic Usage Initialize a cache backend (e.g., file-based):
use ZetaComponents\Cache\Cache;
$cache = new Cache('file', [
'cacheDir' => storage_path('app/cache'),
]);
First Use Case: Storing & Retrieving Data
// Store data (expires in 3600 seconds)
$cache->set('key', 'value', 3600);
// Retrieve data
$value = $cache->get('key'); // Returns 'value' or false if not found
Key Locations
ZetaComponents/Cache/ for backends (File.php, Memcache.php, etc.) and core logic.Multi-Backend Caching
Use different backends for different needs (e.g., file for dev, memcache for prod):
$devCache = new Cache('file', ['cacheDir' => storage_path('app/cache')]);
$prodCache = new Cache('memcache', ['servers' => ['localhost:11211']]);
Automatic Expiration
Leverage set() with a timestamp for manual expiration:
$cache->set('key', 'value', time() + 3600); // Expires in 1 hour
Cache Invalidation Delete keys explicitly:
$cache->delete('key');
Or clear the entire cache (backend-dependent):
$cache->clear();
Tag-Based Caching (Advanced)
Use set() with tags (if supported by the backend) for grouped invalidation:
$cache->set('user:123', $userData, 3600, ['users']);
$cache->deleteByTag('users'); // Invalidate all tagged keys
Laravel Integration Bind the cache to Laravel’s container for dependency injection:
$app->singleton('cache', function () {
return new Cache('file', ['cacheDir' => storage_path('app/cache')]);
});
Then inject via constructor:
public function __construct(private Cache $cache) {}
Middleware for Cached Responses Use the cache to store full HTTP responses (e.g., API results):
$response = $cache->get('api:users');
if (!$response) {
$response = Http::get('https://api.example.com/users');
$cache->set('api:users', $response, 3600);
}
Fallback Logic Combine with Laravel’s cache system for redundancy:
$value = $cache->get('key') ?: Cache::get('key');
No Built-in Laravel Support
Cache::store() compatibility).Cache API.Backend-Specific Quirks
storage_path('app/cache') and ensure permissions:
mkdir -p storage/app/cache && chmod -R 775 storage/app/cache
memcache, redis) and server setup. Test connections early:
try {
$cache = new Cache('memcache', ['servers' => ['localhost:11211']]);
} catch (\Exception $e) {
Log::error('Cache server unreachable: ' . $e->getMessage());
}
No Automatic Tagging
class TaggedCache {
public function set($key, $value, $ttl, array $tags) {
$this->cache->set($key, $value, $ttl);
foreach ($tags as $tag) {
$this->cache->set("tag:$tag:$key", 1, $ttl);
}
}
public function deleteByTag($tag) {
$keys = $this->cache->get("tag:$tag:*");
// ... delete each key
}
}
Serialization Issues
serialize()/unserialize():
$cache->set('key', serialize($complexObject));
$object = unserialize($cache->get('key'));
No Cache Events
if ($cache->get('key')) {
Log::debug('Cache hit for key: key');
}
Check Backend Status Verify the backend is working:
if (!$cache->isSupported()) {
throw new \RuntimeException('Unsupported cache backend');
}
Inspect Cache Contents List all keys (file backend only):
$keys = $cache->getKeys(); // If supported
// Or manually scan the directory
Handle Exceptions Wrap cache operations in try-catch:
try {
$value = $cache->get('key');
} catch (\Exception $e) {
Log::error('Cache error: ' . $e->getMessage());
// Fallback to database or other source
}
Custom Backends
Extend ZetaComponents\Cache\Backend to create new storage adapters (e.g., DynamoDB, S3):
class S3CacheBackend extends Backend {
public function get($key) { /* ... */ }
public function set($key, $value, $ttl) { /* ... */ }
// ...
}
Decorators for Logging/Metrics Wrap the cache to add functionality:
class LoggingCache {
public function __construct(private Cache $cache) {}
public function get($key) {
$start = microtime(true);
$value = $this->cache->get($key);
Log::debug("Cache get($key) took " . (microtime(true) - $start) . "s");
return $value;
}
}
Fallback Chain Implement a chain of caches (e.g., try memcache, fall back to file):
class FallbackCache {
public function __construct(private array $backends) {}
public function get($key) {
foreach ($this->backends as $backend) {
if ($value = $backend->get($key)) {
return $value;
}
}
return false;
}
}
How can I help you explore Laravel packages today?