Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Predis Adapter Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cache/predis-adapter predis/predis
    

    Ensure predis/predis is installed as a dependency (required by the adapter).

  2. 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
            ],
        ],
    ],
    
  3. 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;
    

Implementation Patterns

Core Workflows

  1. 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')]);
    
  2. Hierarchical Caching: Combine with Laravel's cache drivers (e.g., file + Redis) for fallback:

    $stack = Cache::stack(['redis', 'file']); // Redis first, file as fallback
    
  3. Connection Management: Reuse a single Predis\Client instance across cache pools for efficiency:

    $client = app(Client::class); // Laravel DI
    $cache = new PredisCachePool($client);
    

Integration Tips

  • 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
    

Gotchas and Tips

Pitfalls

  1. Key Collisions: Always configure a prefix in the adapter options to avoid conflicts with other Redis users:

    'options' => ['prefix' => 'app_']
    
  2. Connection Handling:

    • Predis Client Lifecycle: The adapter does not manage the Predis\Client lifecycle. Ensure the client is properly connected before use.
    • Reconnection: Handle connection drops gracefully (e.g., wrap operations in a retry loop):
      try {
          $cache->getItem('key')->get();
      } catch (Predis\Connection\ConnectionException $e) {
          // Reconnect or log
      }
      
  3. Tagging Limitations:

    • Tags are not automatically synchronized across clusters. Use a single Redis instance for tagged caches.
    • Bulk tag operations (e.g., getTags()) can be slow for large datasets. Limit tag usage to high-level categories.
  4. 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()]);
    

Debugging

  • Enable Predis Logging: Configure Predis to log commands for debugging:
    $client = new Client(['log' => ['predis.log', 'debug']]);
    
  • Check Redis Keys: Use redis-cli to inspect keys:
    redis-cli KEYS "laravel_cache_*"
    

Extension Points

  1. 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);
        }
    }
    
  2. 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
        }
    });
    
  3. Metrics: Instrument the adapter to track hit/miss ratios or latency:

    $cache->getItemPool()->addListener(new MetricsListener());
    

Configuration Quirks

  • TTL Granularity: Redis stores TTLs in seconds. The adapter converts Laravel's minutes/hours to seconds internally.
  • Cluster Support: For Redis Cluster, ensure the Predis\Client is configured with cluster: true and the adapter will handle sharding automatically.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui