stratadox/hydrator

v6.0.1 2020-11-14 11:33 UTC

This package is auto-updated.

Last update: 2024-09-14 20:20:15 UTC


README

Build Status codecov Infection Minimum PhpStan Level Scrutinizer Code Quality Maintainability Latest Stable Version License

Implements Latest Stable Version License

轻量级 hydrator,适用于各种 hydrate 用途。尽情 hydrate 吧!

安装

使用 composer 安装

composer require stratadox/hydrator

这是什么?

Hydrator 包存在于对象反序列化的上下文中。当从数据源加载数据时,它非常有用。

hydrate 一个对象,就是为其属性分配值。

Hydrator 填充其他对象的字段。

hydrating 通常与 Instantiation 一起工作;创建空对象的过程。

如何使用它?

基本对象

最基本的用法如下

<?php
use Stratadox\Hydrator\ObjectHydrator;

$hydrator = ObjectHydrator::default();
$thing = new Thing();

$hydrator->writeTo($thing, [
    'foo'      => 'Bar.',
    'property' => 'value',
]);

assert($thing->foo === 'Bar.');
assert($thing->getProperty() === 'value');

默认 hydrator 要求 hydrate 对象可以访问其所有自己的属性。

当这种情况不成立时,例如当某些属性是父级的私有属性时,可以使用 reflective hydrator

<?php
use Stratadox\Hydrator\ReflectiveHydrator;

$hydrator = ReflectiveHydrator::default();

集合对象

为了 hydrate 集合对象,Hydrator 包提供 MutableCollectionHydrator,适用于大多数集合类

<?php
use Stratadox\Hydrator\MutableCollectionHydrator;

$hydrator = MutableCollectionHydrator::default();
$collection = new SplFixedArray;

$hydrator->writeTo($collection, ['foo', 'bar']);

assert(2 === count($collection));

MutableCollectionHydrator 通过修改集合对象来进行 hydrating。当然,当您的集合是 不可变 时,这将不起作用,在这种情况下应该使用 ImmutableCollectionHydrator

它还能做什么?

hydrator 可以被装饰以扩展其功能。

映射

要使用 hydration mapping 转换输入数据,可以使用 Mapping 装饰器

<?php
use Stratadox\HydrationMapping\IntegerValue;
use Stratadox\HydrationMapping\StringValue;
use Stratadox\Hydrator\MappedHydrator;
use Stratadox\Hydrator\ObjectHydrator;

$hydrator = MappedHydrator::using(
    ObjectHydrator::default(), 
    StringValue::inProperty('title'),
    IntegerValue::inProperty('rating'),
    StringValue::inPropertyWithDifferentKey('isbn', 'id')
);

$book = new Book;
$hydrator->writeTo($book, [
    'title'  => 'This is a book.',
    'rating' => 3,
    'isbn'   => '0000000001'
]);

观察

可以通过两种方式观察 hydrating 过程:在 hydrating 之前或之后。

要观察 hydrating 过程在 hydrating 开始之前,使用

use Stratadox\Hydrator\ObjectHydrator;
use Stratadox\Hydrator\ObserveBefore;

$hydrator = ObserveBefore::hydrating(ObjectHydrator::default(), new MyCustomObserver());

要观察 hydrating 过程在 hydrating 完成之后,使用

use Stratadox\Hydrator\ObjectHydrator;
use Stratadox\Hydrator\ObserveAfter;

$hydrator = ObserveAfter::hydrating(ObjectHydrator::default(), new MyCustomObserver());

观察者必须是一个 HydrationObserver。它将接收到对象实例和输入数据。