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

Credis Laravel Package

colinmollenhour/credis

A lightweight PHP Redis client focused on performance and reliability. Provides a simple API built on the native phpredis extension, with support for connections, pipelines, transactions, and cluster/sentinel use cases—ideal for Laravel and other PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require colinmollenhour/credis
    
    • No additional config needed for standalone mode (uses PHP's stream_socket_client).
    • For phpredis integration, ensure phpredis is installed (pecl install redis) and enable it in php.ini.
  2. First Connection

    use Credis\Client;
    
    // Standalone mode (no phpredis dependency)
    $client = new Client('tcp://127.0.0.1:6379');
    
    // Wrapped phpredis mode (if available)
    $client = new Client('tcp://127.0.0.1:6379', ['wrapped' => true]);
    
  3. First Use Case: Caching a View

    $cacheKey = 'view_homepage';
    $cached = $client->get($cacheKey);
    
    if (!$cached) {
        $cached = view('home')->render();
        $client->setex($cacheKey, 3600, $cached); // Cache for 1 hour
    }
    echo $cached;
    

Where to Look First

  • Documentation (if available; check for README/usage examples).
  • Client class (src/Client.php) for core methods.
  • Connection class (src/Connection.php) for low-level details (e.g., connection pooling).
  • Tests (tests/) for edge-case examples (e.g., pub/sub, transactions).

Implementation Patterns

Core Workflows

1. Simple Key-Value Operations

// Set/get with TTL
$client->setex('user:123:token', 3600, $token);

// Atomic increment
$client->incr('counter');

// Pipeline for batch ops
$pipeline = $client->pipeline();
$pipeline->set('key1', 'value1');
$pipeline->set('key2', 'value2');
$pipeline->execute();

2. Pub/Sub (Standalone Mode Only)

$pub = new Client('tcp://127.0.0.1:6379');
$sub = new Client('tcp://127.0.0.1:6379');

// Publisher
$pub->publish('channel', 'message');

// Subscriber (blocking)
$sub->subscribe(['channel'], function ($message, $channel) {
    log($message);
});

3. Transactions

$client->multi()
    ->set('tx_key', 'tx_value')
    ->incr('tx_counter')
    ->exec();

4. Connection Management

  • Reuse connections (credis pools connections by default).
  • Custom connection options:
    $client = new Client('tcp://127.0.0.1:6379', [
        'timeout' => 2.5,
        'retry_interval' => 100,
        'read_timeout' => 1.0,
    ]);
    

Integration Tips

  • Laravel Integration: Use credis as a drop-in replacement for Laravel’s Redis driver by binding it in config/app.php:
    'redis' => [
        'client' => Credis\Client::class,
        'options' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'wrapped' => env('REDIS_WRAPPED', false),
        ],
    ];
    
  • Fallback Logic: Wrap credis calls in a try-catch to handle connection drops gracefully:
    try {
        $value = $client->get('key');
    } catch (ConnectionException $e) {
        // Fallback to DB or default value
        $value = 'default';
    }
    
  • Standalone vs. Wrapped:
    • Use standalone for lightweight deployments (e.g., Docker, serverless).
    • Use wrapped (phpredis) for high-performance needs (e.g., local dev, high-traffic apps).

Gotchas and Tips

Pitfalls

  1. Standalone Mode Limitations:

    • No support for Redis clusters (use phpredis wrapped mode for clustering).
    • Pub/Sub works but may have higher latency than phpredis.
    • No Lua scripting (standalone mode only supports basic commands).
  2. Connection Pooling:

    • Credis reuses connections, but long-running scripts (e.g., CLI jobs) may leak connections.
    • Fix: Explicitly close connections in long-running processes:
      $client->close();
      
  3. Serialization:

    • Credis uses PHP’s serialize() by default, which may cause issues with:
      • Large objects (e.g., closures, resources).
      • Non-serializable data (e.g., DateTimeImmutable in some PHP versions).
    • Workaround: Use JSON or a custom serializer:
      $client->set('key', json_encode($data));
      
  4. Timeouts:

    • Standalone mode has higher latency than phpredis. Adjust timeouts if Redis is remote:
      $client = new Client('tcp://remote-redis:6379', ['timeout' => 3.0]);
      
  5. Atomic Operations:

    • Not all phpredis atomic commands (e.g., HINCRBYFLOAT) are supported in standalone mode.
    • Check: Supported Commands.

Debugging Tips

  • Enable Logging:
    $client = new Client('tcp://127.0.0.1:6379', [
        'logger' => function ($message) {
            error_log($message);
        },
    ]);
    
  • Check Connection State:
    if (!$client->ping()) {
        throw new RuntimeException('Redis connection failed');
    }
    
  • Test Locally: Use redis-cli to verify keys/commands work before debugging in code:
    redis-cli SET test "value"
    redis-cli GET test
    

Extension Points

  1. Custom Commands: Extend Client to add missing commands (e.g., for Redis modules like RedisJSON):
    class ExtendedClient extends Client {
        public function jsonSet($key, $path, $data) {
            return $this->call('JSON.SET', [$key, $path, json_encode($data)]);
        }
    }
    
  2. Middleware: Add pre/post-processing to commands:
    $client->addMiddleware(function ($command, $args) {
        array_unshift($args, 'prefix:');
        return [$command, $args];
    });
    
  3. Event Listeners: Hook into connection events (e.g., retry logic):
    $client->on('connect', function () {
        log('Redis connected');
    });
    

Config Quirks

  • wrapped Mode:
    • Requires phpredis extension and ext-redis enabled in php.ini.
    • Verify:
      if (!extension_loaded('redis')) {
          throw new RuntimeException('phpredis extension required for wrapped mode');
      }
      
  • Sentinel/Cluster:
    • Not supported in standalone mode. Use phpredis wrapped mode with:
      $client = new Client([
          'scheme' => 'redis+sentinel',
          'host' => 'mymaster,myslave',
          'port' => 26379,
          'database' => 0,
      ]);
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor