PHPackages                             greenbean/db-hydration - 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. greenbean/db-hydration

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

greenbean/db-hydration
======================

Lightweight, explicit, type-safe hydration system for mapping database rows into DTOs.

00PHP

Since Dec 9Pushed 5mo agoCompare

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

READMEChangelogDependenciesVersions (1)Used By (0)

greenbean/db-hydration
======================

[](#greenbeandb-hydration)

A lightweight, explicit, type-safe PHP 8.3 library for **hydrating PHP objects from database rows**, without requiring an ORM, annotations, attributes, or complex metadata systems.

This library is ideal for applications that:

- Prefer writing SQL rather than generating it
- Use DTOs or readonly value objects
- Want predictable hydration without magical reflection
- Require nested object hydration from JOINed queries
- Want a small, focused library instead of an entire ORM layer

Designed to be framework-agnostic and extremely fast.

---

Features
--------

[](#features)

- **Simple, explicit mappings** (no annotations or attributes)
- **Hydrator** for mapping flat SQL rows to DTOs
- **EmbeddedObject** for nested hydration (JOIN results)
- **DbResults** to hydrate directly from a `PDOStatement` iterator
- **IndexedDbResults** for key-indexed hydration (e.g., `$users[$id]`)
- **Zero dependencies**
- **No reflection**
- **Supports custom value objects**, `fromString()`, and callables
- **Automatic JSON decoding**
- **Strict error handling for mismatched schemas**

---

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

[](#installation)

```
composer require greenbean/db-hydration
```

Requires **PHP 8.3+**.

---

Basic Usage
===========

[](#basic-usage)

1. Define a DTO
---------------

[](#1-define-a-dto)

```
final readonly class UserDto
{
    public function __construct(
        public UserId $id,
        public string $email,
        public DateTimeImmutable $createdAt,
    ) {}
}
```

---

2. Define a mapping
-------------------

[](#2-define-a-mapping)

```
use Greenbean\DbHydration\HydrationMapping;

final class UserMapping implements HydrationMapping
{
    public static function map(): array
    {
        return [
            'id'         => UserId::class,
            'email'      => 'string',
            'created_at' => DateTimeImmutable::class,
        ];
    }
}
```

---

3. Hydrate rows with the Hydrator
---------------------------------

[](#3-hydrate-rows-with-the-hydrator)

```
$hydrator = Hydrator::fromMapping(new UserMapping());

$rows = $pdo->query('SELECT id, email, created_at FROM users')
            ->fetchAll(PDO::FETCH_ASSOC);

$users = $hydrator->hydrateRows(UserDto::class, $rows);
```

---

Nested Hydration with JOINs
===========================

[](#nested-hydration-with-joins)

DTOs:

```
final readonly class ProfileDto
{
    public function __construct(
        public string $bio,
        public int $age,
    ) {}
}

final readonly class UserWithProfileDto
{
    public function __construct(
        public UserId $id,
        public string $email,
        public ProfileDto $profile,
    ) {}
}
```

Mapping:

```
final class ProfileMapping implements HydrationMapping
{
    public static function map(): array
    {
        return [
            'bio' => 'string',
            'age' => 'int',
        ];
    }
}
```

Create hydrators:

```
$profileHydrator = Hydrator::fromMapping(new ProfileMapping(), 'profile');

$userHydrator = Hydrator::fromMapping(
    new UserMapping(),
    prefix: 'u',
    injected: [],
    new EmbeddedObject(
        name: 'profile',
        prefix: 'profile',
        dtoClass: ProfileDto::class,
        hydrator: $profileHydrator
    )
);
```

SQL example:

```
SELECT
    u.id              AS u_id,
    u.email           AS u_email,
    p.bio             AS profile_bio,
    p.age             AS profile_age
FROM users u
LEFT JOIN profiles p ON p.user_id = u.id;
```

Hydrate:

```
$users = $userHydrator->hydrateRows(UserWithProfileDto::class, $rows);
```

---

Streaming Hydration
===================

[](#streaming-hydration)

DbResults
---------

[](#dbresults)

```
$stmt = $pdo->query('SELECT id, email, created_at FROM users');

$results = new DbResults($hydrator, UserDto::class, $stmt);

foreach ($results as $user) {
    // $user is UserDto
}
```

IndexedDbResults
----------------

[](#indexeddbresults)

```
$stmt = $pdo->query('SELECT id, email, created_at FROM users');

$results = new IndexedDbResults('id', $hydrator, UserDto::class, $stmt);

foreach ($results as $id => $user) {
    // keyed by ID
}
```

---

Mapping Rules
=============

[](#mapping-rules)

TypeMeaning`int`Cast to integer`string`Cast to string`bool`Cast to boolean`json`Decode JSON into associative array`ClassName`Uses `fromString()` or constructor`callable`Developer-defined custom mapper---

Error Handling
==============

[](#error-handling)

The hydrator throws exceptions for:

- Missing required columns
- Missing embedded columns
- Unrecognized mapping types
- Type conversion failures

Failures are **explicit and loud**, to catch mistakes early.

---

Requirements
============

[](#requirements)

- PHP **8.3+**
- PDO
- Composer

---

License
=======

[](#license)

MIT License.

---

Contributing
============

[](#contributing)

Pull requests are welcome. Please include:

- A clear summary of the change
- Tests where applicable
- Real-world examples when adding new features

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance49

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/5069750197c1041a9861733b8125c3c6adf154f05e35b1c8dc2a9608cc1722e2?d=identicon)[NotionCommotion](/maintainers/NotionCommotion)

---

Top Contributors

[![NotionCommotion](https://avatars.githubusercontent.com/u/2005437?v=4)](https://github.com/NotionCommotion "NotionCommotion (1 commits)")

### Embed Badge

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

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

###  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)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

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

Reliese Components for Laravel Framework code generation.

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

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

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