PHPackages                             phpdot/redis - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. phpdot/redis

ActiveLibrary[Caching](/categories/caching)

phpdot/redis
============

Coroutine-safe Redis client wrapping ext-redis with auto-reconnect, exponential backoff, exception translation, and a pool connector for phpdot/pool.

v0.1.1(1mo ago)02MITPHP &gt;=8.5

Since Jul 18Compare

[ Source](https://github.com/phpdot/redis)[ Packagist](https://packagist.org/packages/phpdot/redis)[ RSS](/packages/phpdot-redis/feed)WikiDiscussions Synced 1w ago

READMEChangelogDependencies (12)Versions (6)Used By (0)

phpdot/redis
============

[](#phpdotredis)

Coroutine-safe Redis client for PHP 8.4+. Wraps [ext-redis](https://github.com/phpredis/phpredis) `\Redis` with auto-reconnect, exponential backoff, exception translation, and a pool connector for `phpdot/pool`.

One `RedisConnection` owns one `\Redis` socket. Under Swoole, borrow a connection per coroutine through a pool so no two coroutines ever interleave commands on one socket — the same pattern `phpdot/mongodb` uses.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Install](#install)
- [Quick Start](#quick-start)
- [Architecture](#architecture)
- [RedisConnection](#redisconnection)
    - [RedisConfig](#redisconfig)
    - [Lifecycle](#lifecycle)
    - [Resilience](#resilience)
- [Coroutine Safety](#coroutine-safety)
- [Connection Pooling](#connection-pooling)
- [Exception Handling](#exception-handling)
- [Escape Hatch](#escape-hatch)
- [API Reference](#api-reference)

---

Install
-------

[](#install)

```
composer require phpdot/redis
```

Requires PHP 8.4+, `ext-redis` ^6.0, and `phpdot/contracts` ^1.4.

---

Quick Start
-----------

[](#quick-start)

```
use PHPdot\Redis\Config\RedisConfig;
use PHPdot\Redis\RedisConnection;

$connection = new RedisConnection(new RedisConfig(
    host: '127.0.0.1',
    port: 6379,
    password: 'secret',
    database: 0,
));
$connection->connect();

// Reach the underlying \Redis for commands
$connection->getClient()->set('hello', 'world');
$connection->getClient()->get('hello'); // 'world'

$connection->close();
```

---

Architecture
------------

[](#architecture)

```
RedisConfig (readonly value object)
        │
        ▼
RedisConnection ── getClient() ──► \Redis  (ext-redis)
        ▲
        │ owns lifecycle
RedisConnector ──implements──► PHPdot\Contracts\Pool\ConnectorInterface

```

- **`RedisConfig`** — immutable connection parameters (`#[Config('redis')]`).
- **`RedisConnection`** — lifecycle + the raw `\Redis` seam. Mirrors `phpdot/mongodb`'s `MongoConnection`.
- **`RedisConnector`** — adapts `RedisConnection` to the pool contract. Mirrors `MongoConnector`. Depends only on `phpdot/contracts`, so the package works without `phpdot/pool` (FPM, CLI, scripts).

---

RedisConnection
---------------

[](#redisconnection)

### RedisConfig

[](#redisconfig)

```
new RedisConfig(
    host: '127.0.0.1',     // TCP host (ignored when path is set)
    port: 6379,            // TCP port (ignored when path is set)
    path: '',              // Unix socket path; supersedes host/port when set
    password: '',          // AUTH password (Redis 5-). Empty skips AUTH.
    username: '',          // ACL username (Redis 6+). Empty = password-only AUTH.
    database: 0,           // SELECT index after connect
    timeout: 0.0,          // connect timeout, seconds (0 = unlimited)
    retryInterval: 0,      // ext-redis reconnect delay, ms
    readTimeout: 0.0,      // read timeout, seconds
    tls: false,            // connect over TLS (prefixes host with tls://)
    ssl: [],               // stream SSL context options (CA, cert, verify…)
    maxRetries: 3,         // connect-attempt retries, exponential backoff
    persistent: false,     // use pconnect (off by default — pool owns lifecycle)
    context: [],           // catch-all passed as ext-redis' $context arg
);
```

### Lifecycle

[](#lifecycle)

```
$connection->connect();          // establish + AUTH + SELECT + PING
$connection->isConnected();      // local flag, no server round-trip
$connection->ping();             // round-trip PING → bool
$connection->ensureConnected();  // throws ConnectionException if down
$connection->reconnect();        // close() then connect()
$connection->close();            // idempotent
$connection->getConfig();        // RedisConfig
$connection->getClient();        // \Redis (throws if not connected)
```

### Resilience

[](#resilience)

`connect()` retries up to `maxRetries` times with exponential backoff (100ms → 200ms → 400ms…). AUTH failures (`NOAUTH`, `WRONGPASS`) throw `AuthenticationException` immediately and are not retried. All other connection failures accumulate and throw `ConnectionException` once the retry budget is exhausted.

---

Coroutine Safety
----------------

[](#coroutine-safety)

`ext-redis` commands are blocking socket I/O. Two coroutines sharing one `\Redis` interleave request/reply bytes and corrupt each other — this is the footgun `phpdot/redis-ql`'s own docs warn about.

`phpdot/redis` makes the safe pattern trivial: **pool connections, borrow one per coroutine**. Each pooled `RedisConnection` wraps exactly one `\Redis`; a coroutine borrows it, runs commands via `getClient()`, and returns it. No socket is ever shared across concurrent coroutines.

---

Connection Pooling
------------------

[](#connection-pooling)

`RedisConnector` implements `PHPdot\Contracts\Pool\ConnectorInterface`, so `phpdot/pool` can hold and manage `RedisConnection` instances:

```
use PHPdot\Pool\Pool;
use PHPdot\Pool\PoolConfig;
use PHPdot\Redis\Config\RedisConfig;
use PHPdot\Redis\RedisConnector;

$pool = new Pool(
    new RedisConnector(new RedisConfig()),
    PoolConfig::default(),
);

// Borrow a connection per coroutine
$connection = $pool->borrow();
try {
    $connection->getClient()->set('key', 'value');
} finally {
    $pool->release($connection);
}
```

The connector depends only on `phpdot/contracts` — `phpdot/pool` is **not** a runtime requirement, so the package stays usable in non-pooled runtimes (FPM, CLI one-shots).

---

Exception Handling
------------------

[](#exception-handling)

```
RedisException (extends RuntimeException)
├── ConnectionException        // connect failure after retries; carries getHost()
└── AuthenticationException    // AUTH / ACL denial

```

`RedisException` from `ext-redis` is caught and translated inside `connect()`; `RedisConnection`'s own methods throw `PHPdot\Redis\Exception\*` types only.

```
use PHPdot\Redis\Exception\AuthenticationException;
use PHPdot\Redis\Exception\ConnectionException;

try {
    $connection->connect();
} catch (AuthenticationException $e) {
    // bad credentials — do not retry
} catch (ConnectionException $e) {
    // unreachable after retries; $e->getHost() tells you which endpoint
}
```

---

Escape Hatch
------------

[](#escape-hatch)

`getClient(): \Redis` returns the underlying ext-redis instance for any command the wrapper does not surface. This is the primary consumer seam — `phpdot/cache`'s `RedisDriver`, `phpdot/session`'s `RedisHandler`, and `phpdot/redis-ql`'s `PhpRedisClient` can all receive a pooled `\Redis` through it.

---

API Reference
-------------

[](#api-reference)

### RedisConfig API

[](#redisconfig-api)

MethodReturnsNotes`connectHost()``string`socket path or `tls://`-prefixed host`buildContext()``?array`merged stream/SSL context, or `null``getHostString()``string`socket path or `host:port` for errors### RedisConnection API

[](#redisconnection-api)

MethodReturnsThrows`connect()``void``ConnectionException`, `AuthenticationException``close()``void`never`isConnected()``bool`never`ping()``bool`never`ensureConnected()``void``ConnectionException``reconnect()``void``ConnectionException`, `AuthenticationException``getClient()``\Redis``ConnectionException``getConfig()``RedisConfig`never### RedisConnector API

[](#redisconnector-api)

Implements `PHPdot\Contracts\Pool\ConnectorInterface`.

MethodReturnsNotes`connect()``object`fresh connected `RedisConnection``isAlive(object)``bool`type-guarded + `ping()``close(object)``void`type-guarded, never throws

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance93

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

5

Last Release

36d ago

PHP version history (2 changes)v1.0.0PHP &gt;=8.4

v0.1.0PHP &gt;=8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/62e82421bda4b5d6ba9a47ba6d88caca060dcd0d1a2862f351f3a97657385db0?d=identicon)[phpdot](/maintainers/phpdot)

---

Tags

redisswoolephpredisconnection-poolcoroutine-safephpdotext-redis

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/phpdot-redis/health.svg)

```
[![Health](https://phpackages.com/badges/phpdot-redis/health.svg)](https://phpackages.com/packages/phpdot-redis)
```

###  Alternatives

[ukko/phpredis-phpdoc

@phpdoc extension phpredis for IDE autocomplete

214519.0k13](/packages/ukko-phpredis-phpdoc)[cache/redis-adapter

A PSR-6 cache implementation using Redis (PhpRedis). This implementation supports tags

534.2M27](/packages/cache-redis-adapter)[longman/laravel-lodash

Add more functional to Laravel

9798.0k](/packages/longman-laravel-lodash)[mix/redis-subscriber

Redis native protocol Subscriber based on Swoole coroutine

152.0M5](/packages/mix-redis-subscriber)[vetruvet/laravel-phpredis

Use phpredis as the redis connection in Laravel

43127.8k](/packages/vetruvet-laravel-phpredis)[swoft/redis

swoft redis component

12172.1k17](/packages/swoft-redis)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
