PHP code example of antoninmasek / simple-hydrator

1. Go to this page and download the library: Download antoninmasek/simple-hydrator 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/ */

    

antoninmasek / simple-hydrator example snippets


$data = ['name' => 'John', 'age' => 42];

class Human extends \AntoninMasek\SimpleHydrator\DataObject
{
    public string $name;
    
    public int $age;
}

Human::fromArray($data);

$human = Hydrator::hydrate(Human::class, $data);

$human = Human::fromArray($data);

$imageData = [
    "ExifImageWidth" => 4032,
    "ExifImageHeight" => 3024,
]

class ImageData
{
    public int $width;
    public int $height;
}

use AntoninMasek\SimpleHydrator\Attributes\Key;

class ImageData
{
    #[Key('ExifImageWidth')]
    public int $width;
    
    #[Key('ExifImageHeight')]
    public int $height;
}

$car = [
    'brand' => 'Chevrolet',
    'type'  => 'Camaro',
    'keys'  => [
        [
            'name'      => 'main',
            'is_active' => true,
        ],
        [
            'name'      => 'secondary',
            'is_active' => false,
        ],
    ],
];

use AntoninMasek\SimpleHydrator\Attributes\Collection;

class Car
{
    public string $type;
    public string $brand;
    public ?ClassThatNeedsCustomCaster $customCaster;

    #[Collection(Key::class)]
    public ?array $keys;
}

$person = Human::make()
    ->firstName('John')
    ->lastName('Doe')
    ->kids(3);

$person = Human::make()
    ->set('firstName', 'John')
    ->set('lastName', 'Doe')
    ->set('kids', 3);

class DateTimeCaster extends Caster
{
    public function cast(mixed $value): ?DateTime
    {
        if (is_null($value)) {
            return null;
        }

        return new DateTime($value);
    }
}

Caster::registerCaster(DateTime::class, function ($value) {
    if (is_null($value)) {
        return null;
    }

    return new DateTime($value);
});

Caster::setCasters([
    YourObject::class => YourObjectCaster::class,
    YourSecondObject::class => AnotherCaster::class,
]);

Caster::registerCaster(YourObject::class, YourObjectCaster::class);

Caster::clearCasters();