elisdn/php-hydrator

简单对象注水器

1.0.0 2017-07-21 14:14 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:43:19 UTC


README

该库允许从数组中注水对象,并将原始对象的值提取到数组中。

安装

使用 composer 安装

composer require elisdn/php-hydrator

使用示例

从关联数组中注水对象

$post = $this->hydrator->hydrate(Post::class, [
    'id' => $id,
    'date' => $date,
    'title' => $title,
])

通过属性列表提取对象值到数组

$data = $this->hydrator->extract($post, ['id', 'date', 'title'])

例如,如果我们有 Post 实体

class Post
{
    private $id;
    private $title;
    private $date;

    public function __construct($id, $title)
    {
        $this->id = $id;
        $this->title = $title;
        $this->date = new DateTimeImmutable();
    }
    
    public function getId()
    {
        return $this->id;
    }
    
    public function getTitle()
    {
        return $this->title;
    }
}

然后我们可以在任何仓库类中使用该注水器

class SqlPostRepository implements PostRepository
{
    private $db;
    private $hydrator;

    public function get($id): Post
    {
        if (!$row = $this->db->selectOne('posts', ['id' => $id])) {
            throw new NotFoundException('Post not found.');
        }
    
        return $this->hydrator->hydrate(Post::class, [
            'id' => $row['id'],
            'date' => DateTimeImmutable::createFromFormat('Y-m-d', $row['create_date']),
            'title' => $row['title'],
        ]);
    }

    public function persist(Post $post): void
    {
        $data = $this->hydrator->extract($post, ['id', 'date', 'title'])
    
        $this->db->insert('posts', [
            'id' => $data['id'],
            'create_date' => $data['date']->format('Y-m-d'),
            'title' => $data['title'],
        );
    }
}