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

Phpredis Bundle Laravel Package

dawen/phpredis-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require dawen/phpredis-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Dawen\PhpRedisBundle\DawenPhpRedisBundle::class => ['all' => true],
    ];
    
  2. Configuration Define Redis connection parameters in config/packages/dawen_php_redis.yaml:

    dawen_php_redis:
        clients:
            default:
                host: '127.0.0.1'
                port: 6379
                database: 0
                password: null
                timeout: 0
                read_timeout: 0
    
  3. First Use Case Inject the Redis client into a service/controller:

    use Dawen\PhpRedisBundle\Client\RedisClientInterface;
    
    class MyService
    {
        public function __construct(private RedisClientInterface $redis)
        {
        }
    
        public function cacheUserData(int $userId, array $data): void
        {
            $this->redis->hMSet("user:$userId", $data);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Key-Value Operations Use set/get for simple caching:

    $this->redis->set('cache_key', 'value', 3600); // Expires in 1 hour
    $value = $this->redis->get('cache_key');
    
  2. Hashes for Structured Data Store user profiles with hMSet/hGetAll:

    $this->redis->hMSet('user:1', ['name' => 'John', 'email' => 'john@example.com']);
    $userData = $this->redis->hGetAll('user:1');
    
  3. Lists for Queues Push/pop from a queue:

    $this->redis->rPush('queue:jobs', json_encode(['task' => 'send_email']));
    $job = $this->redis->rPop('queue:jobs');
    
  4. Sets for Unique Collections Track unique visitors:

    $this->redis->sAdd('visitors:today', $userId);
    $count = $this->redis->sCard('visitors:today');
    
  5. Sorted Sets for Leaderboards Rank users by score:

    $this->redis->zAdd('leaderboard', 100, $userId);
    $rank = $this->redis->zRank('leaderboard', $userId);
    

Integration Tips

  • Symfony Cache Integration Use Redis as a cache backend by configuring framework/cache in config/packages/framework.yaml:

    framework:
        cache:
            app: cache.adapter.redis
            default_memcached_provider: 'redis://default'
    
  • Doctrine Cache Configure Redis for Doctrine caching in config/packages/doctrine.yaml:

    doctrine:
        orm:
            metadata_cache_driver: 'redis'
            query_cache_driver: 'redis'
            result_cache_driver: 'redis'
    
  • Event-Driven Workflows Use Redis pub/sub for real-time updates:

    $this->redis->publish('user:updated', json_encode(['id' => 1]));
    $this->redis->subscribe(['user:updated'], function ($message) {
        // Handle update
    });
    

Gotchas and Tips

Pitfalls

  1. Connection Management

    • The bundle does not handle connection pooling or failover by default. Use a connection manager or implement retry logic for critical operations.
    • Example retry logic:
      try {
          $this->redis->getConnection()->ping();
      } catch (\RedisException $e) {
          // Reconnect or throw
      }
      
  2. Missing Methods

    • blPop, brPop, and sort are not implemented. Use raw PhpRedis calls if needed:
      $this->redis->getConnection()->blPop(['queue:jobs'], 5); // 5-second timeout
      
  3. Thread Safety

    • Redis connections are not thread-safe. Ensure each request uses its own connection or manage connections carefully in multi-threaded environments.
  4. Serialization

    • Always serialize/deserialize data manually (e.g., json_encode/json_decode) to avoid corruption.
  5. Configuration Overrides

    • The bundle does not support dynamic configuration changes at runtime. Rebuild the Redis client if settings change.

Debugging Tips

  1. Enable Redis Logging Configure the underlying PhpRedis client to log commands:

    dawen_php_redis:
        clients:
            default:
                # ...
                log: '%kernel.debug%'
    
  2. Check Connection Status Use ping to verify connectivity:

    if (!$this->redis->ping()) {
        throw new \RuntimeException('Redis connection failed');
    }
    
  3. Monitor Performance Use info to check Redis server stats:

    $info = $this->redis->info();
    

Extension Points

  1. Custom Clients Extend the base client to add domain-specific methods:

    class CustomRedisClient extends AbstractRedisClient
    {
        public function getUserData(int $userId): array
        {
            return $this->hGetAll("user:$userId");
        }
    }
    
  2. Middleware for Operations Add pre/post-processing logic:

    $this->redis->getConnection()->registerScript('myScript.lua');
    
  3. Event Listeners Subscribe to Redis events (e.g., key expiration) using the PhpRedis event system:

    $this->redis->getConnection()->registerScript('eventScript.lua');
    
  4. Testing Use a mock Redis client in tests:

    $this->redis = $this->createMock(RedisClientInterface::class);
    $this->redis->method('get')->willReturn('mocked_value');
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed