cache/predis-adapter
PSR-6 cache pool implementation backed by Predis (Redis) from the PHP Cache organization. Create a Predis\Client and wrap it in PredisCachePool for fast, standards-compliant caching with shared features like tagging and hierarchy support.
Installation:
composer require cache/predis-adapter predis/predis
Ensure predis/predis is installed as a dependency (required by the adapter).
Basic Configuration:
Define a Redis client configuration in config/cache.php (Laravel) or your DI container:
'stores' => [
'redis' => [
'driver' => 'predis',
'connection' => 'default', // Matches Predis client config
'options' => [
'prefix' => 'laravel_cache_', // Optional: Avoid key collisions
],
],
],
First Use Case: Inject the cache pool via Laravel's service container or manually:
use Cache\Adapter\Predis\PredisCachePool;
use Predis\Client;
$client = new Client(['scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379]);
$cache = new PredisCachePool($client);
Use PSR-6 methods:
$cache->set('key', 'value', 3600); // Expires in 1 hour
$item = $cache->getItem('key');
$value = $item->isHit() ? $item->get() : null;
Tag-Based Caching: Leverage tagging for bulk operations (e.g., invalidate all user-related caches):
$cache->getItem('user:123')->set('John Doe');
$cache->getItem('user:123')->tag(['users', 'premium_users']);
// Invalidate all tagged items
$cache->deleteItems([...$cache->getTags('users')]);
Hierarchical Caching: Combine with Laravel's cache drivers (e.g., file + Redis) for fallback:
$stack = Cache::stack(['redis', 'file']); // Redis first, file as fallback
Connection Management:
Reuse a single Predis\Client instance across cache pools for efficiency:
$client = app(Client::class); // Laravel DI
$cache = new PredisCachePool($client);
Laravel-Specific: Publish the config for customization:
php artisan vendor:publish --tag=predis-cache-config
Extend Laravel's CacheManager to support the adapter:
Cache::extend('predis', function ($app) {
return new PredisCachePool($app['predis']);
});
PSR-6 Compliance: Use the adapter with libraries expecting PSR-6 (e.g., Symfony Cache):
$cache = new PredisCachePool($client);
$symfonyCache = new Symfony\Component\Cache\Adapter\TagAwareAdapter(
new Symfony\Component\Cache\Adapter\PredisAdapter($cache)
);
Async Operations: Offload cache writes to a queue (e.g., Laravel Queues) for performance:
Cache::later()->put('key', 'value', 3600); // Queue the write
Key Collisions:
Always configure a prefix in the adapter options to avoid conflicts with other Redis users:
'options' => ['prefix' => 'app_']
Connection Handling:
Predis\Client lifecycle. Ensure the client is properly connected before use.try {
$cache->getItem('key')->get();
} catch (Predis\Connection\ConnectionException $e) {
// Reconnect or log
}
Tagging Limitations:
getTags()) can be slow for large datasets. Limit tag usage to high-level categories.Serialization:
The adapter uses PHP's serialize() by default. For complex objects, implement __serialize()/__unserialize() or use a custom serializer:
$cache->setItem('key', $item, 3600, ['serializer' => new JsonSerializer()]);
$client = new Client(['log' => ['predis.log', 'debug']]);
redis-cli to inspect keys:
redis-cli KEYS "laravel_cache_*"
Custom Serialization: Extend the adapter to support custom serializers:
class JsonCacheItem extends PredisCacheItem {
public function setData($data) {
$this->data = json_encode($data);
}
public function get() {
return json_decode($this->data, true);
}
}
Event Listeners:
Hook into cache events (e.g., CacheItemPool::clear()) for analytics or side effects:
$cache->getItemPool()->addListener(new class implements CacheItemPoolListenerInterface {
public function onClear(CacheItemPoolClearEvent $event) {
// Log cache clears
}
});
Metrics: Instrument the adapter to track hit/miss ratios or latency:
$cache->getItemPool()->addListener(new MetricsListener());
Predis\Client is configured with cluster: true and the adapter will handle sharding automatically.How can I help you explore Laravel packages today?