PHP code example of solbianca / hydrator

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

    

solbianca / 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.');

$hydrator = new \SolBianca\Hydrator\Hydrator();

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

  OR

$data = $hydrator->extract($post, ['id', 'title']); // extract id and title form object
save_to_database($data);

$data = load_from_database();

$hydrator = new \SolBianca\Hydrator\Hydrator();

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

$data = load_from_database();

$hydrator = new \SolBianca\Hydrator\Hydrator();

$post = get_post();
$post = $hydrator->hydrate($post, $data);
echo $post->getTitle();