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

Redis Bundle Laravel Package

snc/redis-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require snc/redis-bundle
    

    Ensure ext-redis is installed (preferred) or fall back to Predis.

  2. Configuration: Add Redis to your config/packages/snc_redis.yaml:

    snc_redis:
        clients:
            default:
                type: predis # or 'phpredis'
                alias: default
                dsn: redis://127.0.0.1:6379
    
  3. First Use Case: Inject the Redis client into a service/controller:

    use SNC\RedisBundle\Client;
    
    class MyService {
        public function __construct(private Client $redis) {}
    
        public function cacheData(string $key, string $value, int $ttl = 3600) {
            $this->redis->setex($key, $ttl, $value);
        }
    }
    

Where to Look First

  • Documentation: docs/ (especially usage.md and configuration.md).
  • Default Client: The default client is auto-configured if no other clients are defined.
  • Predis vs. PhpRedis: Check composer.json for ext-redis presence; use phpredis if available.

Implementation Patterns

Common Workflows

  1. Caching:

    // Set with TTL
    $this->redis->setex('user:123:data', 3600, json_encode($data));
    
    // Get and auto-delete (e.g., for rate limiting)
    $value = $this->redis->get('temp:key');
    $this->redis->del('temp:key');
    
  2. Pub/Sub:

    // Subscribe in a background process
    $pubsub = $this->redis->pubsubLoop();
    $pubsub->subscribe(['channel:events']);
    $pubsub->listen();
    
  3. Transactions:

    $this->redis->multi()
        ->set('key1', 'value1')
        ->incr('counter')
        ->exec();
    
  4. Pipelining (for batch operations):

    $pipeline = $this->redis->pipeline();
    $pipeline->set('key1', 'value1');
    $pipeline->set('key2', 'value2');
    $pipeline->execute();
    

Integration Tips

  • Dependency Injection: Tag services needing Redis with snc_redis.client to auto-wire the correct client:

    services:
        App\Service\MyService:
            tags: ['snc_redis.client:default']
    
  • Environment-Specific Clients: Use %env(REDIS_URL)% in dsn for dynamic configurations:

    dsn: redis://%env(REDIS_URL)%/0
    
  • Connection Pooling: Reuse clients (e.g., in a singleton service) to avoid connection overhead.

  • Laravel-Specific: If using Laravel, alias the bundle’s client to Laravel’s container:

    // In a service provider
    $this->app->bind(\SNCRedisBundle\Client::class, function ($app) {
        return $app->make('snc_redis.client.default');
    });
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • Default timeout is 2.5 seconds. Increase via options.timeout in config if Redis is slow:
      options:
          timeout: 5.0
      
    • Debugging: Use redis-cli ping to verify server connectivity.
  2. Predis vs. PhpRedis Behavior:

    • Some methods (e.g., hScan) have slight syntax differences. Test both backends if switching.
    • Fix: Use the same method signatures as Predis if unsure.
  3. Serialization:

    • Redis stores data as strings. Use serialize()/unserialize() or JSON for complex objects:
      $this->redis->set('user:1', serialize($user));
      $user = unserialize($this->redis->get('user:1'));
      
  4. Memory Leaks:

    • Unbound keys or large values can bloat Redis. Use memory_usage() to monitor:
      $this->redis->info('memory');
      
  5. Symfony Cache vs. Redis:

    • Avoid mixing Symfony’s Cache component with raw Redis calls for the same keys to prevent inconsistencies.

Debugging

  • Enable Logging: Add to config/packages/monolog.yaml:

    handlers:
        snc_redis:
            type: stream
            path: "%kernel.logs_dir%/snc_redis.log"
            level: debug
            channels: ["snc_redis"]
    

    Then enable Redis logging in snc_redis.yaml:

    logging: true
    
  • Common Errors:

    • Connection refused: Check Redis server (redis-server running? Firewall?).
    • Invalid argument: Verify dsn format (e.g., redis://user:pass@host:port/db).
    • Fix: Use redis:// (not tcp://) and ensure credentials are URL-encoded.

Extension Points

  1. Custom Clients: Define additional clients in snc_redis.yaml:

    clients:
        cache:
            type: phpredis
            alias: cache
            dsn: redis://cache:6379/1
    

    Inject via snc_redis.client.cache.

  2. Middleware: Use Symfony’s kernel.request event to wrap Redis calls in middleware (e.g., for retries):

    $event->getRequest()->attributes->set('redis_retries', 3);
    
  3. Event Listeners: Subscribe to Redis events (e.g., key expiration) via snc_redis.event_listener:

    services:
        App\Listener\RedisKeyListener:
            tags: ['snc_redis.event_listener']
    
  4. Testing: Use snc_redis.test client for tests:

    clients:
        test:
            type: predis
            dsn: "redis://localhost:6379/15" # Isolated DB
    

    Inject via snc_redis.client.test in test services.

Performance Tips

  • Pipeline Batch Operations: Reduce round-trips for bulk writes/reads (e.g., 100 SET operations in one pipeline).
  • Use Hashes for Structured Data:
    $this->redis->hSet('user:1', [
        'name' => 'John',
        'email' => 'john@example.com',
    ]);
    
  • Compress Large Values: Use gzip before storing blobs:
    $compressed = gzcompress($data);
    $this->redis->set('large:data', $compressed);
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver