PHPackages                             eril/db-model-entity - 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. eril/db-model-entity

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

eril/db-model-entity
====================

A lightweight, fluent, and efficient database toolkit separating query logic from data mutations.

v1.0.0(3w ago)00MITPHPPHP ^8.1CI passing

Since May 20Pushed 3w agoCompare

[ Source](https://github.com/erilshackle/db-model-entity-php)[ Packagist](https://packagist.org/packages/eril/db-model-entity)[ RSS](/packages/eril-db-model-entity/feed)WikiDiscussions main Synced 1w ago

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

DBME (Database Model Entity)
============================

[](#dbme-database-model-entity)

A lightweight, fluent, and highly efficient PHP Database Toolkit designed to separate raw CRUD persistence operations from advanced data querying. By splitting responsibilities into distinct execution layers, DBME gives you Active Record features without the overhead or architectural pollution of typical heavy ORMs.

[![PHP Version](https://camo.githubusercontent.com/acffb6ae1962992d26e4466782832787e79504a6250f80d732c4283458b9f497/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75652e737667)](https://php.net)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

Key Architectural Concepts
--------------------------

[](#key-architectural-concepts)

Unlike monolith ORMs, DBME isolates its database operations into three specialized architectural pillars via a unified entry facade:

- **`SqlExecutor` (Direct CRUD):** Handles targeted database write routines (`create`, `update`, `delete`) and primary key lookups without builder baggage.
- **`ModelQuery` (Advanced Querying):** A fluent, stateful query builder dedicated entirely to complex data filtration, aggregations, and subquery isolation (e.g., smart counting with `GROUP BY`).
- **`Entity` &amp; `EntityCollection` (Domain Layer):** Encapsulates single rows into memory-efficient objects equipped with active dirty-state tracking (preventing redundant database roundtrips) and rich array capabilities.

---

Architecture Overview
---------------------

[](#architecture-overview)

 ```
graph TD
    Facade[ModelEntity Facade] -->|::table| Executor[SqlExecutor Layer]
    Facade -->|::query| MQ[ModelQuery Layer]

    Executor -->|Pure Mutation| DB[(Database Server)]
    MQ -->|Fluent Selects| DB

    DB -.->|Hydrates Single Row| Entity[Entity Object]
    DB -.->|Hydrates Multiple Rows| Collection[EntityCollection]

    classDef primary fill:#2563eb,stroke:#1e40af,color:#fff,stroke-width:2px;
    classDef secondary fill:#475569,stroke:#334155,color:#fff,stroke-width:2px;
    classDef storage fill:#16a34a,stroke:#166534,color:#fff,stroke-width:2px;

    class Facade primary;
    class Executor,MQ secondary;
    class DB,Entity,Collection storage;
```

      Loading ---

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

[](#installation)

Install the package via Composer (adjust repository path as needed):

```
composer require eril/db-model-entity
```

---

Quick Start &amp; Usage
-----------------------

[](#quick-start--usage)

### 1. Connection Initialization

[](#1-connection-initialization)

You can initialize a brand new standalone PDO instance directly or register an existing connection/lazy-loading closure (ideal for framework integrations).

```
use Eril\DBME\Database\DB;

// Option A: Direct Connection
DB::connect('mysql:host=127.0.0.1;dbname=app_db;charset=utf8mb4', 'root', 'secret');

// Option B: Lazy-Loading Connection Resolver (e.g., sharing a framework instance)
DB::registerConnection(function() {
    return Container::get('pdo');
});

// Option C: Lazy-Loading Connection Resolver (e.g., Own Database Class)
DB::registerConnection([Database::class, "getConnection"]);
```

### 2. Standard CRUD Operations (`::table`)

[](#2-standard-crud-operations-table)

Use the `table` entry point when mutating data or performing explicit row mutations. It returns a dedicated `SqlExecutor` instance.

```
use Eril\DBME\ModelEntity;

// Create a new record (Returns an Entity object)
$user = ModelEntity::table('users')->create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'status' => 'pending'
]);

// Update multiple target records based on conditions
ModelEntity::table('users')
    ->where('status', '=', 'pending')
    ->update(['status' => 'inactive']);

// Delete target records safely
ModelEntity::table('users')->delete(15); // Delete by ID
```

### 3. Advanced Querying (`::query`)

[](#3-advanced-querying-query)

Use the `query` entry point when you need a fluent query builder interface, conditional filters, pagination, or database calculations. It returns a `ModelQuery` instance.

```
use Eril\DBME\ModelEntity;

// Fetch a collection using fluent criteria
$users = ModelEntity::query('users', 'u')
    ->where('u.status', '=', 'active')
    ->where('u.age', '>', '21')
    ->orderBy('u.created_at', 'DESC')
    ->get(); // Returns an EntityCollection

// Run high-performance aggregates directly on the server level
$averageAge = ModelEntity::query('users')->aggregate('AVG', 'age');
$totalRevenue = ModelEntity::query('orders')->aggregate('SUM', 'total_amount');

// Smart counting protects against broken counts when using GROUP BY
$count = ModelEntity::query('orders')
    ->groupBy('customer_id')
    ->count();
```

### 4. Active Record &amp; Memory Snapshots (`Entity`)

[](#4-active-record--memory-snapshots-entity)

When an `Entity` is loaded from the database, it captures an internal snapshot of its database state. Calling `update()` executes dirty-checking to compile an optimal SQL payload, updating only mutated properties.

```
// Modifying object properties dynamically
$user = ModelEntity::query('users')->first();
$user->name = 'Jane Doe';

// The update routine safely merges and checks both manual changes and arguments
// If nothing changed compared to the loading snapshot, no database query is executed.
$user->update(['status' => 'verified']);

// Self-deletion capabilities
$user->delete();
```

### 5. Collection Operations (`EntityCollection`)

[](#5-collection-operations-entitycollection)

The `EntityCollection` provides high-utility, in-memory array manipulation tools without querying the database server redundantly.

```
$activeUsers = $users->filter(fn($user) => $user->status === 'active');

// Pluck a specific column as a scalar array
$emails = $users->pluck('email'); // ['john@example.com', 'jane@example.com']

// Look up a specific record loaded into memory by any key-value criterion
$targetUser = $users->find('id', 42);

if (!$users->isEmpty()) {
    $firstOne = $users->first();
}
```

### 6. Atomic Database Transactions

[](#6-atomic-database-transactions)

Wrap complex, cross-table mutation streams securely inside database transactions. Any uncaught exception automatically rolls back changes.

```
use Eril\DBME\Database\DB;
use Eril\DBME\ModelEntity;

DB::transaction(function () {
    ModelEntity::table('accounts')->where('id', 1)->update(['balance' => 400]);
    ModelEntity::table('accounts')->where('id', 2)->update(['balance' => 800]);

    // If an error occurs here, both balance changes are completely rolled back.
});
```

---

Code Quality Standards
----------------------

[](#code-quality-standards)

This library is designed keeping static analysis tools (`PHPStan`, `Psalm`) in mind. All classes include strict inline generics documentation, precise typehints, and clear object property mappings.

License
-------

[](#license)

This toolkit is open-sourced software licensed under the [MIT License](https://www.google.com/search?q=LICENSE).

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance96

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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

Unknown

Total

1

Last Release

21d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/74083037?v=4)[Eril TS Carvalho](/maintainers/erilshackle)[@erilshackle](https://github.com/erilshackle)

---

Top Contributors

[![erilshackle](https://avatars.githubusercontent.com/u/74083037?v=4)](https://github.com/erilshackle "erilshackle (8 commits)")

---

Tags

active-recordcomposer-packagedatabaseormpdophpquery-builderdatabaseormpdoactive-recordquery builder

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/eril-db-model-entity/health.svg)

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

###  Alternatives

[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.

836.0k](/packages/tommyknocker-pdo-database-class)[flightphp/active-record

Micro Active Record library in PHP, support chain calls, events, and relations.

163.6k11](/packages/flightphp-active-record)

PHPackages © 2026

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