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

Fast object hydration without violating incapsulation


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);

Чтобы увидеть комментарии, нужно быть участником сообщества

Регистрация