PHPackages                             hank21014/synth - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. hank21014/synth

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

hank21014/synth
===============

A lightweight PHP utility for data dehydration and hydration.

0.1.2(4mo ago)04MITPHPPHP &gt;=8.1CI passing

Since Feb 19Pushed 4mo agoCompare

[ Source](https://github.com/hank21014/php-synth)[ Packagist](https://packagist.org/packages/hank21014/synth)[ RSS](/packages/hank21014-synth/feed)WikiDiscussions main Synced today

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

[![tests](https://github.com/hank21014/php-synth/actions/workflows/tests.yml/badge.svg?branch=main&event=push)](https://github.com/hank21014/php-synth/actions/workflows/tests.yml)

💧 PHP Synth: Seamless Data Hydration
====================================

[](#-php-synth-seamless-data-hydration)

Synth is a lightweight PHP utility designed to bridge the gap between complex objects and serializable arrays. By using custom "Synth," you can dehydrate objects into structured arrays and hydrate them back into their original state with type safety and zero fuss.

🌟 Why Synth?
------------

[](#-why-synth)

- Architecture Friendly: Keep your Entities/DTOs "lean" by moving transformation logic into dedicated Synth classes.
- Custom Mapping: Decouple your internal object structure from your external data schema (API, Cache, or Queue).

🛠️ Installation
---------------

[](#️-installation)

Install the package via Composer:

```
composer require hank21014/synth
```

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Define your Entity

[](#1-define-your-entity)

A plain PHP class. No traits or inheritance required.

```
namespace App;

class User
{
    public function __construct(public string $name, public array $friends = []) {}
}
```

### 2. Create a Synth

[](#2-create-a-synth)

Implement the Synth interface to define how your object should be transformed.

```
namespace App\Synths;

use App\User;
use Hank21014\Synth\Contracts\Synth;
use Hank21014\Synth\SynthManager;

/**
 * @implements Synth
 */
class UserSynth implements Synth
{
    #[\Override]
    public static function synthesizedClass(): string
    {
        return User::class;
    }

    #[\Override]
    public function dehydrate(SynthManager $synth, $subject): array
    {
        return [
            '' => $subject->name,
            '' => $synth->dehydrate($subject->friends)
        ];
    }

    #[\Override]
    public function hydrate(SynthManager $synth, array $payload)
    {
        /**
         * The $payload matches the array structure returned by your dehydrate method.
         */
        return new User(
            name: $payload[''],
            friends: $synth->hydrate($payload[''])
        );
    }
}
```

### 3. Usage

[](#3-usage)

Register your Synth and start transforming data.

```
use App\User;
use App\Synths\UserSynth;
use Hank21014\Synth\SynthManager;

$manager = new SynthManager();

// Register the synth with a unique type identifier
$manager->add('user', UserSynth::class);

$user = new User('hank');

// --- Dehydrate ---
$dehydrated = $manager->dehydrate($user);
/**
 * Result $dehydrated:
 * Notice how each User object is recursively wrapped with the [SYNTH] flag.
 * This metadata allows the manager to know exactly which Synth to use for each level.
*/
/*
[
    "[SYNTH]" => true,
    "type" => "user",
    "payload" => [
        "" => "john",
        "" => [
            [
                "[SYNTH]" => true,
                "type" => "user",
                "payload" => [
                    "" => "hank",
                    "" => [
                         [
                            "[SYNTH]" => true,
                            "type" => "user",
                            "payload" => [
                                "" => "joy",
                                "" => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
]
*/

// --- Hydrate ---
$hydrated = $manager->hydrate($dehydrated);
// $hydrated is now a fresh instance of App\User
```

💡 Key Concepts
--------------

[](#-key-concepts)

### Dehydration

[](#dehydration)

Taking a "living" object and drying it out into a portable array format (perfect for JSON or Database storage).

### Hydration

[](#hydration)

Taking that array data and "watering" it back into a PHP object.

### The Metadata Wrapper

[](#the-metadata-wrapper)

Synth automatically wraps your payload with a `[SYNTH]` flag and a type key. This allows the SynthManager to automatically know which class to instantiate during hydration.

Tip

**Balance Uniqueness vs. Length**

When customizing the identity key, choose a value that is unique enough to avoid data collisions but short enough to keep your dehydrated payloads efficient.

### Primitive Handling

[](#primitive-handling)

Synth handles non-object types via a built-in PrimitiveSynth. This ensures that your basic data structures remain intact while objects are being transformed.

TypeStrategyDetailScalar/NullPass-throughValues like `int`, `float`, `string`, `bool` or `null` are returned without modification.Standard ArrayRecursiveEvery element inside the array is checked and processed by the `SynthManager`.Synthesized ArrayDelegatedArrays containing the `[SYNTH]` flag are passed to their respective specialized Synths.⚙️ Advanced Configuration
-------------------------

[](#️-advanced-configuration)

### Customizing the Identity Key

[](#customizing-the-identity-key)

```
use Hank21014\Synth\SynthesizableArray;

// Must be called before any hydration/dehydration occurs
SynthesizableArray::identityBy('');
```

### Configuring Global Synths

[](#configuring-global-synths)

Synth comes with built-in support for common PHP types:

Synth ClassTarget Type\\Hank21014\\Synth\\Synths\\DateTimeSynth\\DateTime\\Hank21014\\Synth\\Synths\\DateTimeImmutableSynth\\DateTimeImmutableTo disable all global synths:

```
use Hank21014\Synth\Synths;

Synths::withoutGlobalSynths();
```

To customize global synths:

```
use Hank21014\Synth\Synths;

Synths::useGlobalSynths([...]);
```

Important

Global configuration must be performed before the SynthManager is initialized. Calling these methods after instantiation will have no effect on existing manager instances.

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance75

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

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.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

133d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1e5da7a80374a6072eaafa0bf3c1e9042bad6139922157e2a5219c1fad277620?d=identicon)[hank21014](/maintainers/hank21014)

---

Top Contributors

[![hank21014](https://avatars.githubusercontent.com/u/145869903?v=4)](https://github.com/hank21014 "hank21014 (21 commits)")

---

Tags

phpserializationhydrationdehydration

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/hank21014-synth/health.svg)

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

###  Alternatives

[apache/avro

Apache Avro™ is a data serialization system.

3.3k60.2k3](/packages/apache-avro)

PHPackages © 2026

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