PHP code example of hank21014 / synth

1. Go to this page and download the library: Download hank21014/synth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hank21014 / synth example snippets


namespace App;

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

namespace App\Synths;

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

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

    #[\Override]
    public function dehydrate(SynthManager $synth, $subject): array
    {
        return [
            '<name>' => $subject->name,
            '<friends>' => $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['<name>'],
            friends: $synth->hydrate($payload['<friends>'])
        );
    }
}

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" => [
        "<name>" => "john",
        "<friends>" => [
            [
                "[SYNTH]" => true,
                "type" => "user",
                "payload" => [
                    "<name>" => "hank",
                    "<friends>" => [
                         [
                            "[SYNTH]" => true,
                            "type" => "user",
                            "payload" => [
                                "<name>" => "joy",
                                "<friends>" => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
]
*/

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

use Hank21014\Synth\SynthesizableArray;

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

use Hank21014\Synth\Synths;

Synths::withoutGlobalSynths();

use Hank21014\Synth\Synths;

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