PHP code example of samdark / hydrator

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

    

samdark / hydrator example snippets


class Post
{
    private $id;
    protected $title;
    protected $text;

    public function __construct($title, $text)
    {
        $this->id = uniqid('post_', true);
        $this->title = $title;
        $this->text = $text;
    }
   
    public function getId()
    {
        return $this->id;
    }
    
    public function getTitle()
    {
        return $this->title;
    }
    
    public function setTitle($title)
    {
        $this->title = $title;
    }
    
    public function getText()
    {
        return $this->text;
    }
    
    public function setText()
    {
        return $this->text;
    }
}

$post = new Post('First post', 'Hell, it is a first post.');

$postHydrator = new \samdark\hydrator\Hydrator([
    'id' => 'id',
    'title' => 'title',
    'text' => 'text',
]);

$data = $postHydrator->extract($post);
save_to_database($data);


$data = load_from_database();

$postHydrator = new \samdark\hydrator\Hydrator([
    'id' => 'id',
    'title' => 'title',
    'text' => 'text',
]);

$post = $postHydrator->hydrate($data, Post::class);
echo $post->getId();

$data = load_from_database();

$postHydrator = new \samdark\hydrator\Hydrator([
    'title' => 'title',
    'text' => 'text',
]);

$post = get_post();
$post = $postHydrator->hydrateInto($data, $post);
echo $post->getTitle();