Для получения полного доступа
зарегистрируйтесь.
RSS

All snippets tagged with "hydration" tag



samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

After posting about fast hydration I've got response with even faster method that doesn't require extra class. Credits go to Vladimir Chub.

$postHydrator = function(array $data) {
    $this->id = $data['id'];
    $this->title = $data['title'];
    $this->text = $data['text'];
};

$postExtractor = function() {
    return [
        'id' => $this->id,
        'title' => $this->title,
        'text' => $this->text
    ];
}

// $data is from database

$post = new Post();
$hydrator = $postHydrator->bindTo($post, $post);
$hydrator($data);

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

It's important for object oriented programming and domain driven design not to violate incapsulation i.e. what should not be set by developer should be private or protected:

class Post
{
    protected $id;
    protected $title;
    protected $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($text)
    {
        $this->text = $text;
    }
}

When it comes to pesisting data in database and getting it back there's a problem of filling properties we can't set. Usually it's solved by using reflection but it's quite slow when it comes to hundreds of objects. Marco Pivetta posted a better approach which despite being meant for Doctrine internals is quite simple and interesting.

class PostSelfHydratingProxy extends Post
{
    /** zero-argument constructor since this is just a helper class for hydration */
    public function __construct()
    {
    }
    
    public function hydrate($data, Post $object)
    {
		$object->id = $data['id'];
        $object->title = $data['title'];
        $object->text = $data['text'];
    }

    
    public function extract(Post $object)
    {
        return [
            'id' => $object->id,
            'title' => $object->title,
            'text' => $object->text
        ];
    }
}

// $data is from database

$post = new Post();
$proxy = new PostSelfHydratingProxy();
$proxy->hydrate($data, $post);