PHPackages                             faster-php/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. faster-php/db

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

faster-php/db
=============

A drop-in replacement for PDO with connection pooling, lazy connect, auto-reconnect, and prepared statement caching.

1.x-dev(2y ago)02GPL-3.0-or-laterPHPPHP &gt;=8.2

Since Mar 16Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/FasterPHP/db)[ Packagist](https://packagist.org/packages/faster-php/db)[ RSS](/packages/faster-php-db/feed)WikiDiscussions main Synced 1mo ago

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

FasterPHP/Db
============

[](#fasterphpdb)

**FasterPHP/Db** is a high-performance, drop-in replacement for PHP's native `PDO` class. It enhances standard database operations with advanced features designed for robust, modern applications — all while retaining full compatibility with `PDO` interfaces and expectations.

If you're tired of dealing with intermittent MySQL timeouts or disconnects, repetitive statement preparation, or clunky connection logic, this package gives you a clean, extensible, and efficient solution that just works — no learning curve required.

Key features:

- ✅ Drop-in `PDO` replacement (extends `PDO`, not just wraps it)
- 🔁 Auto-reconnect on lost or timed-out connections with configurable retry/backoff
- 🛡️ Transaction-aware reconnect protection
- 🔄 Lazy-loading and internal connection pooling
- ⚡️ Prepared statement caching for reduced overhead
- 📝 Optional PSR-3 logging support
- 🧱 Custom `DbStatement` class for enhanced control

---

🚀 Installation
--------------

[](#-installation)

```
composer require fasterphp/db
```

---

✅ Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- A supported PDO database (e.g. MySQL, PostgreSQL, SQLite, etc.)
- PDO extension (`ext-pdo`)

---

📦 Basic Usage
-------------

[](#-basic-usage)

```
use FasterPhp\Db\Db;

$db = new Db(
    dsn: 'mysql:host=localhost;dbname=mydb',
    username: 'myuser',
    password: 'mysecret',
);

$stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute([':id' => 1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
```

---

🔁 Auto-Reconnect
----------------

[](#-auto-reconnect)

If a connection is lost (e.g. due to a timeout), FasterPhp\\Db automatically reconnects, re-prepares (where necessary), and re-executes the statement.

### Configurable Retry with Exponential Backoff

[](#configurable-retry-with-exponential-backoff)

The `DefaultStrategy` supports configurable retry attempts with exponential backoff:

```
use FasterPhp\Db\Db;
use FasterPhp\Db\Reconnect\DefaultStrategy;

$strategy = new DefaultStrategy(
    maxAttempts: 3,        // Try up to 3 times (default: 1)
    baseDelayMs: 100,      // Start with 100ms delay (default: 100)
    backoffMultiplier: 2.0 // Double the delay each attempt (default: 2.0)
);

$db = new Db(
    dsn: 'mysql:host=localhost;dbname=mydb',
    username: 'myuser',
    password: 'mysecret',
    reconnectStrategy: $strategy
);
```

With these settings, reconnect attempts will wait 100ms, then 200ms, then 400ms between retries.

### Transaction-Aware Reconnect Protection

[](#transaction-aware-reconnect-protection)

Reconnecting mid-transaction would silently lose uncommitted changes. FasterPhp\\Db prevents this by throwing a `DbException` if a reconnectable error occurs during an active transaction:

```
$db->beginTransaction();
$db->exec('INSERT INTO users (name) VALUES ("Alice")');
// If connection is lost here, DbException is thrown instead of reconnecting
// This prevents silent data loss
```

This protection works for both explicit transactions (`beginTransaction()`) and raw SQL transactions (`BEGIN`/`START TRANSACTION`).

### PSR-3 Logging

[](#psr-3-logging)

You can attach a PSR-3 compatible logger to monitor reconnect events:

```
use Psr\Log\LoggerInterface;

$db->setLogger($logger);

// Reconnect events are logged at WARNING level with DSN and error details
```

### Custom Reconnect Strategy

[](#custom-reconnect-strategy)

You can configure reconnect patterns via `Config\ArrayProvider` or inject a custom `ReconnectStrategy` by implementing `Reconnect\StrategyInterface`.

---

⚙️ Statement Caching
--------------------

[](#️-statement-caching)

Prepared statements are cached internally to avoid repeated preparation overhead:

```
$stmt1 = $db->prepare('SELECT * FROM users WHERE id = :id');
$stmt2 = $db->prepare('SELECT * FROM users WHERE id = :id');
// $stmt1 === $stmt2
```

To clear the statement cache (e.g. after schema changes or to free memory):

```
$db->clearStatementCache();
```

---

🔧 Advanced Usage
----------------

[](#-advanced-usage)

### 📡 ConnectionManager

[](#-connectionmanager)

The `ConnectionManager` class enables application-wide connection pooling and shared configuration. It’s ideal for large applications, services, or frameworks that require multiple named database instances or shared lifecycle control.

```
use FasterPhp\Db\ConnectionManager;
use FasterPhp\Db\Config\ArrayProvider;

$config = new ArrayProvider([
    'main' => [
        'dsn' => 'mysql:host=127.0.0.1;dbname=main_db',
        'username' => 'root',
        'password' => '',
        'options' => [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ],
    ],
    'analytics' => [
        'dsn' => 'mysql:host=127.0.0.1;dbname=analytics',
        'username' => 'readonly',
        'password' => '',
    ],
]);

$manager = new ConnectionManager($config);

// Get a shared Db instance
$db = $manager->get('main');
```

> 💡 `ConnectionManager` will automatically reuse idle connections if available.

---

### ⚙️ Configuration Providers

[](#️-configuration-providers)

The `Config\ArrayProvider` class is a simple implementation of the `ProviderInterface` that lets you define connection settings in plain PHP arrays.

To use a different configuration source (like `.env`, JSON, or YAML), implement:

```
interface ProviderInterface {
    public function get(string $name): ?array;
}
```

This keeps your configuration logic separate from your application logic, and makes it easy to test or extend.

---

🧪 Testing
---------

[](#-testing)

Tests require a MySQL server with a `testdb` database. You can configure your environment using `.env` variables or `phpunit.xml`:

```
DB_DSN="mysql:host=127.0.0.1;dbname=testdb"
DB_USER="root"
DB_PASS=""

```

Run tests with:

```
vendor/bin/phpunit
```

To generate a coverage report (requires Xdebug or PCOV):

```
vendor/bin/phpunit --coverage-html build/coverage
```

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! To get started:

1. Fork the repository
2. Create a new branch (`git checkout -b feature/my-feature`)
3. Commit your changes (`git commit -am 'Add feature'`)
4. Push to the branch (`git push origin feature/my-feature`)
5. Open a pull request

---

🧭 Code of Conduct
-----------------

[](#-code-of-conduct)

Please be respectful and constructive in all interactions. We aim to foster a professional, welcoming environment.

---

🔐 Security
----------

[](#-security)

If you discover a security vulnerability, please report it privately via GitHub or email the maintainer. Avoid opening public issues for sensitive disclosures.

---

📄 License
---------

[](#-license)

This package is open-source software licensed under the [MIT license](LICENSE.md).

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance56

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

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

Total

4

Last Release

169d ago

Major Versions

1.x-dev → 2.0.0-rc12025-04-21

### Community

Maintainers

![](https://www.gravatar.com/avatar/0740beda9f1ddf19c5dfc64cd37c338b2371bb4ac3d92e0f6d3c9b0dd4f5becd?d=identicon)[marcusjhdon](/maintainers/marcusjhdon)

---

Top Contributors

[![FasterPHP](https://avatars.githubusercontent.com/u/5726267?v=4)](https://github.com/FasterPHP "FasterPHP (20 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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