samdark/hydrator

允许从对象中提取数据或根据数据创建新的对象,用于持久化状态。支持私有和受保护属性。

资助包维护!
samdark
Patreon

1.0.4 2017-05-17 08:15 UTC

This package is auto-updated.

Last update: 2024-08-25 07:31:03 UTC


README

Hydrator 可以用于两个目的

  • 从类中提取数据并将其存储在持久存储中。
  • 用数据填充对象或创建一个包含数据的类的新实例。

在这两种情况下,它都保存和填充受保护和私有属性,而不调用任何方法,这导致能够以正确封装的数据持久化对象的状态。

Latest Stable Version Total Downloads Build Status

安装

安装此包的首选方式是通过 composer

composer require --prefer-dist samdark/hydrator

使用

假设我们有一个 Post 实体,它表示一篇博客文章。它有一个标题和文本。生成一个唯一的ID来标识它。

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

从数据库加载数据

<?php
$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();