PHPackages                             hongxunpan/db - 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. [Database &amp; ORM](/categories/database)
4. /
5. hongxunpan/db

ActiveLibrary[Database &amp; ORM](/categories/database)

hongxunpan/db
=============

connections for db, such as mysql &amp; redis ...

1.1.0(3w ago)02342MITPHPPHP &gt;=5.6CI passing

Since Oct 12Pushed 3w ago1 watchersCompare

[ Source](https://github.com/HongXunPan/db-connection)[ Packagist](https://packagist.org/packages/hongxunpan/db)[ RSS](/packages/hongxunpan-db/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (3)Dependencies (1)Versions (5)Used By (2)

db-connection
=============

[](#db-connection)

`hongxunpan/db` 提供无框架、无容器依赖的命名连接内核，目前包含：

- Redis；
- MySQLi；
- PDO。

包内不读取项目的 `config()`、`env()`，也不依赖 `simple-framework`。框架或 Module 应在外层完成配置加载、实例构造和容器绑定。

安装
--

[](#安装)

```
composer require hongxunpan/db
```

推荐用法
----

[](#推荐用法)

### 显式构造 Redis

[](#显式构造-redis)

```
use HongXunPan\DB\Redis\Redis;

$redis = new Redis(
    [
        'default' => [
            'host' => 'redis.internal',
            'port' => 6379,
            'timeout' => 1.5,
            'auth' => ['app-user', 'secret'],
            'database' => 1,
            'prefix' => 'app:',
        ],
    ]
);

$connection = $redis->getConnection();
$connection->set('key', 'value');
```

无参数时固定解析名为 `default` 的连接；其他连接必须通过 `getConnection('cache')` 等方式显式指定。

构造实例和调用 `setAsGlobal()` 都不会建立网络连接。首次调用 `getConnection()` 或 静态 `connection()` 时才创建连接；同名连接在当前进程内复用，获取缓存连接时不会 隐藏执行 `PING`。

需要主动重建时使用：

```
$redis->forgetConnection();
$connection = $redis->reconnect();
```

### 容器实例兼容旧静态入口

[](#容器实例兼容旧静态入口)

框架集成层可以把已构造实例登记为全局实例：

```
$redis->setAsGlobal();
```

此后新旧入口使用同一连接池：

```
$redis->getConnection();
Redis::connection();
```

测试或常驻进程需要清理全局实例时：

```
Redis::clearGlobal();
```

Redis 配置
--------

[](#redis-配置)

默认内部 phpredis 适配实现支持：

- `host`、`port`、`timeout`；
- `persistent`、`persistent_id`；
- `retry_interval`、`read_timeout`；
- `auth`，可以是密码字符串或 ACL 的 `[username, password]`；
- `database`；
- `scheme=tcp|tls` 与 `context`；
- `prefix`；
- phpredis 原生 `options`。

旧配置键 `reserved`、`retryInterval`、`readTimeout` 仍会转换到标准键。

常规项目不需要感知 Factory。只有测试或确需替换底层 Client 创建过程时，才实现 `HongXunPan\DB\Redis\Contract\RedisClientFactory`，并通过 `Redis::withClientFactory()` 高级入口创建实例。`Internal\PhpRedisClientFactory`是内部实现，不属于常规公开 API。

旧静态 API
-------

[](#旧静态-api)

已有项目可以继续使用：

```
Redis::setConfig(['host' => '127.0.0.1']);
Redis::connection()->set('key', 'value');
```

静态入口不再隐式创建 localhost 配置。未先调用 `setConfig()`，或请求的连接名不存在时， 会直接抛出 `DBException`。

连接包装
----

[](#连接包装)

`connection()` 和 `getConnection()` 返回对应的 `DBConnectionContract` 子类，例如 `RedisConnection`。普通客户端方法会由包装对象代理到底层连接：

```
$redis->getConnection()->incr('counter');
```

确需访问原生客户端时：

```
$nativeRedis = $redis->getConnection()->getConnection();
```

MySQL 兼容入口
----------

[](#mysql-兼容入口)

原有 MySQLi / PDO 静态配置和连接入口保持可用：

```
\HongXunPan\DB\Mysql\Mysqli\Mysqli::setConfig($config);
$mysqli = \HongXunPan\DB\Mysql\Mysqli\Mysqli::connection();

\HongXunPan\DB\Mysql\Pdo\Pdo::setConfig($config);
$pdo = \HongXunPan\DB\Mysql\Pdo\Pdo::connection();
```

验证
--

[](#验证)

```
composer test
```

测试不连接真实 Redis 或 MySQL，覆盖实例连接池、静态全局代理、延迟创建、显式重连、 旧静态入口和 Redis Client Factory 注入。

更新记录
----

[](#更新记录)

- `1.1.0` 2026-07-25：增加实例连接池、`setAsGlobal()`、显式重连和 Redis Client Factory；
- `1.0.2` 2022-10-15：修正 `connection()` 文档提示；
- `1.0.1` 2022-10-13：修正子类单例隔离；
- `1.0.0` 2022-10-13：提供 Redis、MySQLi 与 PDO 连接。

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance95

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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 ~460 days

Total

4

Last Release

23d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/37c4ffcd9218f6b9722875da1ec37f20b0118651687de5798972f919bd2c1eb4?d=identicon)[HongXunPan](/maintainers/HongXunPan)

---

Top Contributors

[![HongXunPan](https://avatars.githubusercontent.com/u/25816508?v=4)](https://github.com/HongXunPan "HongXunPan (15 commits)")

### Embed Badge

![Health badge](/badges/hongxunpan-db/health.svg)

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

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.8k117.8M121](/packages/jdorn-sql-formatter)[backup-manager/backup-manager

A framework agnostic database backup manager with user-definable procedures and support for S3, Dropbox, FTP, SFTP, and more with drivers for popular frameworks.

1.7k1.6M11](/packages/backup-manager-backup-manager)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M88](/packages/propel-propel1)[insolita/yii2-migration-generator

Set of gii tools for generating files for migration by schema of table , phpdoc or table data

108508.0k5](/packages/insolita-yii2-migration-generator)[xpdo/xpdo

A PDO-based Object/Relational Bridge Library

7088.4k4](/packages/xpdo-xpdo)[voku/session2db

A PHP library acting as a wrapper for PHP's default session handling functions which stores data in a MySQL database, providing both better performance and better security and protection against session fixation and session hijacking.

2920.0k](/packages/voku-session2db)

PHPackages © 2026

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