PHP code example of mordilion / generated-abstract-hydrator

1. Go to this page and download the library: Download mordilion/generated-abstract-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/ */

    

mordilion / generated-abstract-hydrator example snippets


use GeneratedHydrator\Configuration;
use Mordilion\GeneratedAbstractHydrator\ClassGenerator\AbstractHydratorGenerator;
use Mordilion\GeneratedAbstractHydrator\Hydrator\PerformantAbstractHydrator;

function getClassHydrator(string $class): PerformantAbstractHydrator
{
    $config = new Configuration($class);
    $config->setHydratorGenerator(new AbstractHydratorGenerator(PerformantAbstractHydrator::class));
    $hydratorClass = $config->createFactory()->getHydratorClass();

    if (!class_exists($hydratorClass)) {
        throw new \RuntimeException('Could not create Hydrator!');
    }

    /** @var PerformantAbstractHydrator $hydrator */
    $hydrator = new $hydratorClass();

    return $hydrator;
}

use Mordilion\GeneratedAbstractHydrator\Strategy\RecursiveHydrationStrategy;
use Zend\Hydrator\Strategy\DateTimeFormatterStrategy;

class Book
{
    /**
     * @var string
     */
    public $title;
    
    /**
     * @var DateTime
     */
    public $publishedAt;
}

class Author
{
    /**
     * @var string
     */
    public $name;
    
    /**
     * @var string
     */
    public $firstname;
    
    /**
     * @var Book[]
     */
    public $books;
}

// ---

$data = [
    'name' => 'Böll',
    'firstname' => 'Heinrich',
    'books' => [
        ['title' => 'Die schwarzen Schafe', 'publishedAt' => '1951-01-01'],
        ['title' => 'Wo warst du, Adam?', 'publishedAt' => '1951-01-01'],
        ['title' => 'Ansichten eines Clowns', 'publishedAt' => '1963-01-01'],
    ],
];

$bookHydrator = getClassHydrator(Book::class);
$bookHydrator->addStrategy('publishedAt', new DateTimeFormatterStrategy('Y-m-d'));

$authorHydrator = getClassHydrator(Author::class);
$authorHydrator->addStrategy('books', new RecursiveHydrationStrategy(new Book(), $bookHydrator, true));

$object = new Author();
$authorHydrator->hydrate($data, $object);

var_dump($object);