PHPackages                             sav/hydrator-creator - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. sav/hydrator-creator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

sav/hydrator-creator
====================

Hydrating objects through the class constructor

0.2.1(2y ago)014MITPHPPHP ^8.1

Since Jul 15Pushed 2y ago1 watchersCompare

[ Source](https://github.com/sparhokm/hydrator-creator)[ Packagist](https://packagist.org/packages/sav/hydrator-creator)[ RSS](/packages/sav-hydrator-creator/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (5)Versions (4)Used By (0)

Hydrator creator
================

[](#hydrator-creator)

[![Code Coverage](https://camo.githubusercontent.com/e8f115dc29d0bf11073f3dc18df4df7cd6fb294298d0be12d7e38e43f96e7f5a/68747470733a2f2f636f6465636f762e696f2f67682f73706172686f6b6d2f6879647261746f722d63726561746f722f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/sparhokm/hydrator-creator)[![type-coverage](https://camo.githubusercontent.com/96cfb5bdb3e9e77f9ca2b31dae2b7acde6bc6b381aed6ddd9625c178c349ba08/68747470733a2f2f73686570686572642e6465762f6769746875622f73706172686f6b6d2f6879647261746f722d63726561746f722f636f7665726167652e737667)](https://shepherd.dev/github/sparhokm/hydrator-creator)[![psalm-level](https://camo.githubusercontent.com/c04d2a42f21a356fe49ab7ff9ac332d2531f97215f8d5ff2da4ce031a0e802ae/68747470733a2f2f73686570686572642e6465762f6769746875622f73706172686f6b6d2f6879647261746f722d63726561746f722f6c6576656c2e737667)](https://shepherd.dev/github/sparhokm/hydrator-creator)

The library is designed for hydrating objects through the class constructor. Additionally, with the help of expandable attributes, it is possible to add your own data extractors, modifiers, and validators. The attribute can be applied to the class or to parameters.

- [Installation](#installation)
- [Usage](#usage)
    - [Array of objects](#array-of-objects)
    - [Alias for field](#alias-for-field)
    - [Default value](#default-value)
    - [Required value for parameter](#required-value-for-parameter)
    - [Not empty validator](#not-empty-validator)
- [Your own attributes](#your-own-attributes)

**Installation**
----------------

[](#installation)

The package can be installed via composer:

```
composer require sav/hydrator-creator

```

> Note: The current version of the package supports only PHP 8.1 +.

### **Usage**

[](#usage)

```
use Sav\Hydrator\Hydrator;

final class User
{
    public readonly string $email;

    public function __construct(
        string $email,
        public readonly string $name
    ) {
        $this->email = strtolower($email);
    }
}

$data = [
    'email' => 'Test@mail.com',
    'name' => 'Sam',
];

$user = Hydrator::init()->hydrate(User::class, $data);
var_dump($user);
```

Result:

```
object(User) {
  ["email"]=> string(13) "test@mail.com"
  ["name"]=> string(3) "Sam"
}
```

If the property is not of a scalar type, but a class of another object is allowed, it will also be automatically converted. If a class uses one parameter in the constructor, it will be automatically passed to the constructor without the need to specify the exact name. This allows for converting data into simple ValueObjects.

```
use Sav\Hydrator\Hydrator;

final class Item
{
    public function __construct(
        public readonly int $id,
        public readonly string $name,
    ) {
    }
}

final class PriceValueObject
{
    public function __construct(
        private readonly float $value,
    ) {
    }

    public function getValue(): float
    {
        return $this->value;
    }
}

final class OrderItem
{
    public function __construct(
        public readonly Item $product,
        public readonly PriceValueObject $cost,
    ) {
    }
}

$data = [
    'product' => ['id' => 1, 'name' => 'phone'],
    'cost' => 10012.23,
];

$orderItem = Hydrator::init()->hydrate(OrderItem::class, $data);
var_dump($orderItem);
```

Result:

```
object(OrderItem) {
  ["product"]=> object(Item) {
    ["id"]=> int(1)
    ["name"]=> string(5) "phone"
  }
  ["cost"]=> object(PriceValueObject) {
    ["value":"PriceValueObject":private]=> float(10012.23)
  }
}
```

### **Array of objects**

[](#array-of-objects)

If you have an array of objects of a certain class, then you must specify the ArrayOfObjects attribute for it, passing it to which class you need to bring the elements.

Example:

```
use Sav\Hydrator\Hydrator;
use Sav\Hydrator\Attribute\ArrayMap\ArrayOfObjects;

class Product
{
    public function __construct(
        public readonly int $id,
        public readonly DateTimeImmutable $dateCreate,
    ) {
    }
}

class Products
{
    public function __construct(
        #[ArrayOfObjects(Product::class)]
        public readonly array $products
    ) {
    }
}

$data = [
    'products' => [
        ['id' => 1, 'dateCreate' => '2023-01-01'],
        ['id' => 2, 'dateCreate' => '2023-01-02'],
    ],
];
$products = Hydrator::init()->hydrate(Products::class, $data);
var_dump($products);
```

Result

```
object(Products) {
  ["products"]=> array(2) {
    [0]=> object(Product) {
      ["id"]=> int(1)
      ["dateCreate"]=> object(DateTimeImmutable) {
        ["date"]=> string(26) "2023-01-01 00:00:00.000000"
        ["timezone_type"]=> int(0)
        ["timezone"]=> string(3) "UTC"
      }
    }
    [1]=>object(Product) {
      ["id"]=> int(2)
      ["dateCreate"]=> object(DateTimeImmutable) {
        ["date"]=> string(26) "2023-01-02 00:00:00.000000"
        ["timezone_type"]=> int(0)
        ["timezone"]=> string(3) "UTC"
      }
    }
  }
}
```

### **Alias for field**

[](#alias-for-field)

Various possible aliases can be set for the property, which will also be searched in the data source.

```
use Sav\Hydrator\Hydrator;
use Sav\Hydrator\Attribute\ValueExtractor\Alias;

class User
{
    public function __construct(
        private readonly int $id,
        #[Alias('personalPhone')]
        private readonly string $phone,
    ) {
    }
}
```

### **Default value**

[](#default-value)

Using the DefaultValue attribute, you can set a default value for a parameter. You can also set default values using standard php syntax.

```
use Sav\Hydrator\Hydrator;
use Sav\Hydrator\Attribute\ValueModifier\DefaultValue;

class User
{
    public function __construct(
        public readonly int $id,
        #[DefaultValue(new DateTimeImmutable('2023-01-03'))]
        public readonly DateTimeImmutable $dateCreate,
        #[DefaultValue(100, applyForEmpty: true)]
        public readonly int $balance,
        public readonly int $limit = 30,
    ) {
    }
}

$user = Hydrator::init()->hydrate(User::class, ['id' => 1, 'balance' => 0]);
var_dump($user);
```

Result:

```
object(User) {
  ["id"]=> int(1)
  ["dateCreate"]=> object(DateTimeImmutable) {
    ["date"]=> string(26) "2023-01-03 00:00:00.000000"
    ["timezone_type"]=> int(0)
    ["timezone"]=> string(3) "UTC"
  }
  ["balance"]=> int(100)
  ["limit"]=> int(30)
}
```

### **Required value for parameter**

[](#required-value-for-parameter)

The attribute specifies whether a parameter value is required in the input data. The attribute can be applied to the class or to parameters.

```
use Sav\Hydrator\Hydrator;
use Sav\Hydrator\Attribute\RequiredKeyValue;

#[RequiredKeyValue]
class User
{
    public function __construct(
        public readonly ?int $id,
        public readonly int $balance = 3,
    ) {
    }
}

try {
    $user = Hydrator::init()->hydrate(User::class, ['id' => 1]);
} catch(HydratorException $e) {
    echo $e->getMessage();
}
```

Result:

```
balance: Value not exist.

```

### **Not empty validator**

[](#not-empty-validator)

The NotEmpty attribute allows checking the completeness of arguments. It checks only if a value has been assigned to the argument, and it is not null. If the check fails, an exception will be thrown.

```
use Sav\Hydrator\Hydrator;
use Sav\Hydrator\Attribute\ValueValidator\NotEmpty;

class User
{
    public function __construct(
        public readonly int $id,
        #[NotEmpty]
        public readonly int $balance,
    ) {
    }
}

try {
    $user = Hydrator::init()->hydrate(User::class, ['id' => 1, 'balance' => 0]);
} catch(HydratorException $e) {
    echo $e->getMessage();
}
```

Result:

```
balance: Value is empty.

```

**Your own attributes**
-----------------------

[](#your-own-attributes)

To expand the functionality, you can write your own attributes that implement special interfaces depending on their purpose.

- `Sav\Hydrator\Attribute\ValueExtractor` is used to change the search for a parameter value among input data. An example of such an attribute is Alias.
- `\Sav\Hydrator\Attribute\ValueModifier` is needed to transform the found value. An example could be the DefaultValue attribute.
- `\Sav\Hydrator\Attribute\ValueValidator` is used to check extracted and modified data. An example is the NotEmpty attribute that validates empty values.
- `\Sav\Hydrator\Attribute\ArrayMap` is used to define the type of interpretation for values with a specific key. An example is the ArrayOfObjects attribute, which interprets each element of the array as a value of a specified class.

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

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

Total

3

Last Release

996d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b188ec70a89b595be218b427bc68a6378d8e9d77d6de9cd735dfd072f892578?d=identicon)[Starikov Andrey](/maintainers/Starikov%20Andrey)

---

Top Contributors

[![sparhokm](https://avatars.githubusercontent.com/u/6119993?v=4)](https://github.com/sparhokm "sparhokm (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sav-hydrator-creator/health.svg)

```
[![Health](https://phpackages.com/badges/sav-hydrator-creator/health.svg)](https://phpackages.com/packages/sav-hydrator-creator)
```

PHPackages © 2026

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