clue/redis-protocol
Async Redis protocol implementation for PHP. Provides a low-level RESP encoder/decoder and streaming parser for building Redis clients and proxies, often used with ReactPHP. Lightweight, focused, and transport-agnostic for TCP/TLS connections.
Start by installing via Composer:
composer require clue/redis-protocol
This package is not a Redis client—it’s a protocol encoder/decoder. Your first step is to encode a simple command like PING:
use Clue\Redis\Protocol\Protocol;
$protocol = new Protocol();
$encoded = $protocol->encodeCommand('PING'); // Returns raw RESP-encoded string: "*1\r\n$4\r\nPING\r\n"
To parse a server response (e.g., from a raw socket or stream):
$protocol->parse('+PONG' . "\r\n"); // Returns 'PONG'
Begin with the Protocol class and its encodeCommand()/parse() methods—these are your core interfaces.
Non-blocking streams: Use with stream_socket_client() or ReactPHP sockets. Feed incoming bytes incrementally to parse()—it handles partial responses:
$protocol = new Protocol();
while ($data = fread($socket, 8192)) {
$protocol->feed($data);
while ($reply = $protocol->getReply()) {
// Process decoded reply (e.g., array, string, int)
}
}
Batch command encoding: Encode multiple commands into a single payload for pipelining:
$payload = '';
foreach (['SET', 'foo', 'bar'] as $cmd) {
$payload .= $protocol->encodeCommand($cmd);
}
fwrite($socket, $payload);
Test-driven custom clients: Write unit tests for your client logic without network calls—mock the Protocol layer to simulate responses:
$protocol->feed("+OK\r\n");
$protocol->feed(":1\r\n");
// → assert `$protocol->getReply()` returns expected types in order
Extensibility: Subclass Protocol to intercept onReply() or override parsing for logging, metrics, or custom types.
Stream buffering: feed() accumulates data until a full reply is ready. Use getReply() in a loop—don’t assume one feed() = one reply. Missing data can cause it to return null until more bytes arrive.
Bulk/bulk-array parsing: Multi-bulk replies return nested arrays. For commands like HGETALL, expect ['field1', 'value1', 'field2', 'value2']—no associative keys unless you transform it.
Error handling: Redis errors (e.g., ERR) are returned as ErrorReply objects (or strings depending on version). Always check:
$reply = $protocol->parse('-WRONGTYPE');
if ($reply instanceof \Clue\Redis\Protocol\ErrorReply) { /* handle */ }
RESP version compatibility: This package targets RESP2 (Redis <7.2). For newer servers using RESP3, switch to clue/redis-react’s newer client—this library does not support * (map) or ~ (set) types.
No TLS support: You must layer TLS (e.g., tls:// wrappers) yourself. The library handles protocol, not transport security.
Memory efficiency: For high-throughput use, avoid cloning Protocol instances—reuse one per connection to preserve internal buffer state.
How can I help you explore Laravel packages today?