PHP code example of jameshalsall / object-hydrator

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

    

jameshalsall / object-hydrator example snippets


$data = ['name' => 'Frank Turner', 'job_title' => 'Musician'];
$hyrdator = new ObjectConstructorFromArrayHydrator();
$person = $hydrator->hydrate('Person\Employee', $data);



namespace Person;

class Employee
{
    private $name;
    private $jobTitle;
    
    public function __construct($name, $jobTitle)
    {
        $this->name = $name;
        $this->jobTitle = $jobTitle;
    }
}

$data = ['name' => 'Frank Turner', 'job_title' => 'Musician'];
$hyrdator = new ObjectSetterFromArrayHydrator();
$person = $hydrator->hydrate('Person\Employee', $data);



namespace Person;

class Employee
{
    private $name;
    private $jobTitle;
    
    public function setName($name)
    {
        $this->name = $name;
    }
    
    public function setJobTitle($jobTitle)
    {
        $this->jobTitle = $jobTitle;
    }
}

$data = ['name' => 'Frank Turner', 'job_title' => 'Musician'];
$hydrator = new ObjectSetterFromArrayHydrator();
$person = new Person();
$hydrator->hydrate($person, $data);

$data = [['name' => 'Frank Turner', 'job_title' => 'Musician'], ['name' => 'Steve Jobs', 'job_title' => 'CEO']];
$hydrator = new ObjectSetterFromArrayHydrator();
$hydratedObjects = $hydrator->hydrateCollection('Person\Employee', $data);

$data = ['name' => 'Frank Turner', 'job_title' => 'Musician'];
$hydrator = new ObjectConstructorFromArrayHydrator();
$person = $hydrator->hydrate(function ($rawData) {
    if ($rawData['job_title' === 'Musician']) {
        return 'Person\Musician';
    }

    return 'Person\Employee';
}, $data);