PHP code example of fatcode / hydration

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

    

fatcode / hydration example snippets



use FatCode\Hydration\Schema;
use FatCode\Hydration\Type;

class MyUser 
{
    private $id;
    private $name;
    private $age;
    private $interests = [];
    
    public function __construct(int $id, string $name, int $age) 
    {
        $this->id = $id;
        $this->name = $name;
        $this->age = $age;
    }
}

class MyUserSchema extends Schema
{
    protected $id;
    protected $name;
    protected $age;
    protected $interests;
    
    public function __construct()
    {
        $this->id = Type::id();
        $this->name = Type::string();
        $this->age = Type::integer();
        $this->interests = Type::array();
    }
    
    // Target class has to be provided so schema knows to which class it is corresponding.
    public function getTargetClass() : string
    {
        return MyUser::class;
    }
}


use FatCode\Hydration\ObjectHydrator;

$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());


use FatCode\Hydration\ObjectHydrator;

$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());

// Hydration
$bob = $objectHydrator->hydrate(
    [
        'id' => 1,
        'name' => 'Bob',
        'age' => 30,
        'interests' => ['Flowers', 'Judo', 'M1lf$']
    ], 
    MyUser::class
);


use FatCode\Hydration\ObjectHydrator;

$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());
$bob = new MyUser(1, 'Bob', 30);
$dataset = $objectHydrator->extract($bob); // ['id' => 1, 'name' => 'Bob', 'age' => 30, 'interests' => []]