PHPackages                             infocyph/dblayer - 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. infocyph/dblayer

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

infocyph/dblayer
================

High-performance, secure database layer for PHP and multi-driver capabilities

2.0.1(2w ago)0882↑35.2%1MITPHPPHP ^8.4CI passing

Since Apr 10Pushed 1w agoCompare

[ Source](https://github.com/infocyph/DBLayer)[ Packagist](https://packagist.org/packages/infocyph/dblayer)[ RSS](/packages/infocyph-dblayer/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (8)Versions (6)Used By (1)

DBLayer - High-Performance PHP Database Layer
=============================================

[](#dblayer---high-performance-php-database-layer)

[![Security & Standards](https://github.com/infocyph/DBLayer/actions/workflows/security-standards.yml/badge.svg)](https://github.com/infocyph/DBLayer/actions/workflows/security-standards.yml)[![Packagist Downloads](https://camo.githubusercontent.com/100a61b23445e6e65dd56ff1993fefa35b82d29ccee8decb74cadb8cd4003c48/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696e666f637970682f44424c617965723f636f6c6f723d677265656e266c696e6b3d68747470732533412532462532467061636b61676973742e6f72672532467061636b61676573253246696e666f6379706825324644424c61796572)](https://camo.githubusercontent.com/100a61b23445e6e65dd56ff1993fefa35b82d29ccee8decb74cadb8cd4003c48/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696e666f637970682f44424c617965723f636f6c6f723d677265656e266c696e6b3d68747470732533412532462532467061636b61676973742e6f72672532467061636b61676573253246696e666f6379706825324644424c61796572)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](https://opensource.org/licenses/MIT)[![Packagist Version](https://camo.githubusercontent.com/90fc06004e850f71703eea921da43959da030473a986516b96dad27c032ce5d7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696e666f637970682f44424c61796572)](https://camo.githubusercontent.com/90fc06004e850f71703eea921da43959da030473a986516b96dad27c032ce5d7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696e666f637970682f44424c61796572)[![Packagist PHP Version](https://camo.githubusercontent.com/5512d555533960022114690fd06920ddfe3135535df1aa6b1d27cab3666b3a6f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f696e666f637970682f44424c617965722f706870)](https://camo.githubusercontent.com/5512d555533960022114690fd06920ddfe3135535df1aa6b1d27cab3666b3a6f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f696e666f637970682f44424c617965722f706870)[![GitHub Code Size](https://camo.githubusercontent.com/6424a246452bb21394b4110e4db4c54d2783f5ea6d011c8de5989f0b01303018/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f696e666f637970682f44424c61796572)](https://camo.githubusercontent.com/6424a246452bb21394b4110e4db4c54d2783f5ea6d011c8de5989f0b01303018/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f696e666f637970682f44424c61796572)[![Documentation](https://camo.githubusercontent.com/39bee8881758269d11d49721133294a1383d59727a188a2d26537fee478e34aa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f446f63756d656e746174696f6e2d44424c617965722d626c75653f6c6f676f3d72656164746865646f6373266c6f676f436f6c6f723d7768697465)](https://docs.infocyph.com/projects/DBLayer/)

A robust, secure, and feature-rich database abstraction layer for PHP 8.4+ with multi-driver compatibility.

Features
--------

[](#features)

### Core Features

[](#core-features)

- **Query Builder** - Fluent, Laravel-like API
- **Repository Layer** - Thin class-based repositories on top of Query Builder
- **Connection Manager** - Connection pooling + read replicas
- **Replica Strategies** - `random`, `round_robin`, `least_latency`
- **Multi-Driver** - MySQL, PostgreSQL, SQLite
- **Security** - Multi-layer SQL injection protection
- **Transactions** - Nested transactions with savepoints
- **Caching** - Query result caching
- **Profiling** - Performance monitoring
- **Events** - Lifecycle hooks
- **Telemetry** - Query + transaction observability export
- **Pagination** - Length-aware, simple, and cursor pagination

### Performance

[](#performance)

- Microsecond-level benchmark results for core query-builder and transaction paths
- Connection pooling for reuse
- Memory-efficient cursor mode for large datasets

### Security

[](#security)

- Automatic parameterization (all values bound)
- Identifier validation &amp; escaping
- Operator whitelist
- SQL injection pattern detection
- Config-driven hardening with TLS policy controls
- Rate limiting
- Audit logging

Installation
------------

[](#installation)

```
composer require infocyph/dblayer
```

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

[](#quick-start)

### Basic Configuration

[](#basic-configuration)

```
use Infocyph\DBLayer\DB;

// Single connection
DB::addConnection([
    'driver' => 'mysql',
    'host' => 'localhost',
    'port' => 3306,
    'database' => 'myapp',
    'username' => 'root',
    'password' => 'secret',
    'charset' => 'utf8mb4',
]);

// Read replicas
DB::addConnection([
    'driver' => 'mysql',
    'read_strategy' => 'round_robin', // random | round_robin | least_latency
    'read' => [
        ['host' => 'replica1.example.com'],
        ['host' => 'replica2.example.com'],
    ],
    'database' => 'myapp',
    'username' => 'root',
    'password' => 'secret',
]);
```

### Query Controls

[](#query-controls)

```
// Per-query timeout budget (milliseconds)
DB::withQueryTimeout(500, function () {
    DB::select('select * from users');
});

// Absolute deadline relative to now (seconds)
DB::withQueryDeadline(0.25, function () {
    DB::select('select * from users');
});

// Cooperative cancellation check
DB::withQueryCancellation(
    fn () => false,
    fn () => DB::select('select 1')
);
```

### Telemetry

[](#telemetry)

```
DB::enableTelemetry();

DB::select('select 1');
DB::beginTransaction();
DB::rollBack();

$snapshot = DB::telemetry();      // read buffer
$exported = DB::flushTelemetry(); // read + clear
```

### Query Builder

[](#query-builder)

```
// SELECT
$users = DB::table('users')
    ->select('id', 'name', 'email')
    ->where('active', true)
    ->where('age', '>=', 18)
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();

// INSERT
$id = DB::table('users')->insertGetId([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

// UPDATE
DB::table('users')
    ->where('id', $id)
    ->update(['name' => 'Jane Doe']);

// DELETE
DB::table('users')->where('id', $id)->delete();

// Complex queries
$orders = DB::table('orders as o')
    ->join('users as u', 'o.user_id', '=', 'u.id')
    ->leftJoin('products as p', 'o.product_id', '=', 'p.id')
    ->where('o.status', 'completed')
    ->where(function($q) {
        $q->where('o.total', '>', 1000)
          ->orWhere('u.vip', true);
    })
    ->select('o.*', 'u.name as user_name', 'p.name as product_name')
    ->get();

// Aggregates
$count = DB::table('users')->count();
$total = DB::table('orders')->sum('amount');
$average = DB::table('products')->avg('price');
```

### Repository Layer

[](#repository-layer)

```
use Infocyph\DBLayer\DB;

$users = DB::repository('users');

$all = $users->all();
$one = $users->find(1);
$active = $users->get(fn ($q) => $q->where('active', 1));
```

### Choosing APIs (DB vs QueryBuilder vs Repository)

[](#choosing-apis-db-vs-querybuilder-vs-repository)

- Use `DB` for infrastructure concerns: connections, transactions, retries, telemetry, pooling.
- Use `DB::table()` / `QueryBuilder` for ad-hoc SQL shaping: joins, CTEs, dynamic filters, reporting.
- Use `DB::repository()` for reusable table-level rules: tenant scope, soft deletes, optimistic locking, hooks, casts.

If the same table rules appear in multiple call sites, move that logic into a repository-oriented class.

### TableRepository (Repository-Oriented, Non-ORM)

[](#tablerepository-repository-oriented-non-orm)

```
use Infocyph\DBLayer\Repository\TableRepository;
use Infocyph\DBLayer\Query\QueryBuilder;
use Infocyph\DBLayer\Query\Repository;

final class User extends TableRepository
{
    protected static string $table = 'users';
    protected static ?string $connection = 'main';

    protected static function configureRepository(Repository $repository): Repository
    {
        return $repository->enableSoftDeletes()->setDefaultOrder('id', 'desc');
    }

    protected static function configureQuery(QueryBuilder $query): QueryBuilder
    {
        return $query->where('active', '=', 1);
    }
}

$one = User::find(1);                              // Repository method
$rows = User::where('active', '=', 1)->get();     // QueryBuilder method
$stats = User::stats();                            // DB facade method
$reportRows = User::query('reporting')->get();     // Per-call connection override
```

### Transactions

[](#transactions)

```
// Automatic transaction
DB::transaction(function() {
    DB::table('accounts')->where('id', 1)->update(['balance' => 900]);
    DB::table('accounts')->where('id', 2)->update(['balance' => 1100]);
    DB::table('transactions')->insert(['amount' => 100]);
});

// Manual transaction
DB::beginTransaction();
try {
    // ... operations
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}
```

Testing
-------

[](#testing)

```
composer tests
composer test:code
composer test:static:strict
composer test:security:strict
composer release:audit
```

Test execution is driver-aware:

- SQLite-only environments run the base test set.
- If MySQL/PostgreSQL are available (via `DBLAYER_MYSQL_*` / `DBLAYER_PGSQL_*` env vars), matrix tests automatically run for those drivers too.

So total test count increases when more drivers are available.

Benchmarking
------------

[](#benchmarking)

```
composer bench:run
composer bench:quick
composer bench:chart
```

Benchmarks
----------

[](#benchmarks)

Latest `composer bench:quick` sample output:

SubjectModeRSD`benchBuildSelectSql``11.79μs``±0.80%``benchSelectByPrimaryKey``28.20μs``±1.27%``benchTransactionTwoPointReads``20.66μs``±1.61%``benchUpdateSingleColumn``23.45μs``±4.21%`Environment for this sample: PHP 8.5.4, xdebug disabled, opcache disabled, 10 revs x 3 iterations.

Security
--------

[](#security-1)

DBLayer implements multiple layers of security:

1. **Parameterization** - All values automatically bound
2. **Identifier Validation** - Table/column names validated
3. **Operator Whitelist** - Only safe operators allowed
4. **Injection Detection** - Scans for suspicious patterns
5. **Rate Limiting** - Prevents query flooding
6. **Audit Logging** - Tracks all queries

Hardening controls:

- `DB::hardenProduction()` sets `enabled=true`, `strict_identifiers=true`, `require_tls=true`.
- `SecurityMode::OFF` is blocked by default (allow explicitly with `Security::allowInsecureMode(true)`).
- `security.enabled=false` and `security.require_tls=false` require `security.allow_insecure=true`.

Requirements
------------

[](#requirements)

- PHP 8.4+
- ext-pdo
- ext-pdo\_mysql (for MySQL)
- ext-pdo\_pgsql (for PostgreSQL)
- ext-pdo\_sqlite (for SQLite)

Security
--------

[](#security-2)

Protected by [PHPForge](https://github.com/infocyph/PHPForge) — an automated quality and security gate for PHP projects.

---

 **Made with ❤️ for the PHP community**
 [MIT Licensed](LICENSE)
 [Documentation](https://docs.infocyph.com/projects/DBLayer) • [Security](SECURITY.md) • [Code of Conduct](CODE_OF_CONDUCT.md) • [Contributing](CONTRIBUTING.md) • [Report Bug](https://github.com/infocyph/DBLayer/issues) • [Request Feature](https://github.com/infocyph/DBLayer/issues)

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance98

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity55

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

Total

3

Last Release

16d ago

Major Versions

1.0 → 2.02026-05-17

### Community

Maintainers

![](https://www.gravatar.com/avatar/33b750b84ab22f2038ef9b90ee48f2fcdaab6b5698e9f956a89a152466200b63?d=identicon)[abmmhasan](/maintainers/abmmhasan)

---

Top Contributors

[![abmmhasan](https://avatars.githubusercontent.com/u/7711128?v=4)](https://github.com/abmmhasan "abmmhasan (98 commits)")

---

Tags

databasemysqlpdopostgresqlquery-builderrepositorysqlitedatabasemysqlsqlitepostgresqlsqlpdoquery builderrepository

### Embed Badge

![Health badge](/badges/infocyph-dblayer/health.svg)

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

###  Alternatives

[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k605.0M7.0k](/packages/doctrine-dbal)[cycle/database

DBAL, schema introspection, migration and pagination

71777.8k63](/packages/cycle-database)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

826.1k](/packages/tommyknocker-pdo-database-class)[delight-im/db

Safe and convenient SQL database access in a driver-agnostic way

47174.0k7](/packages/delight-im-db)

PHPackages © 2026

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