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.
Installation
composer require colinmollenhour/credis
stream_socket_client).phpredis integration, ensure phpredis is installed (pecl install redis) and enable it in php.ini.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]);
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;
Client class (src/Client.php) for core methods.Connection class (src/Connection.php) for low-level details (e.g., connection pooling).tests/) for edge-case examples (e.g., pub/sub, transactions).// 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();
$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);
});
$client->multi()
->set('tx_key', 'tx_value')
->incr('tx_counter')
->exec();
$client = new Client('tcp://127.0.0.1:6379', [
'timeout' => 2.5,
'retry_interval' => 100,
'read_timeout' => 1.0,
]);
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),
],
];
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';
}
phpredis) for high-performance needs (e.g., local dev, high-traffic apps).Standalone Mode Limitations:
phpredis wrapped mode for clustering).phpredis.Connection Pooling:
$client->close();
Serialization:
serialize() by default, which may cause issues with:
DateTimeImmutable in some PHP versions).$client->set('key', json_encode($data));
Timeouts:
phpredis. Adjust timeouts if Redis is remote:
$client = new Client('tcp://remote-redis:6379', ['timeout' => 3.0]);
Atomic Operations:
phpredis atomic commands (e.g., HINCRBYFLOAT) are supported in standalone mode.$client = new Client('tcp://127.0.0.1:6379', [
'logger' => function ($message) {
error_log($message);
},
]);
if (!$client->ping()) {
throw new RuntimeException('Redis connection failed');
}
redis-cli to verify keys/commands work before debugging in code:
redis-cli SET test "value"
redis-cli GET test
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)]);
}
}
$client->addMiddleware(function ($command, $args) {
array_unshift($args, 'prefix:');
return [$command, $args];
});
$client->on('connect', function () {
log('Redis connected');
});
wrapped Mode:
phpredis extension and ext-redis enabled in php.ini.if (!extension_loaded('redis')) {
throw new RuntimeException('phpredis extension required for wrapped mode');
}
phpredis wrapped mode with:
$client = new Client([
'scheme' => 'redis+sentinel',
'host' => 'mymaster,myslave',
'port' => 26379,
'database' => 0,
]);
How can I help you explore Laravel packages today?