Aaronbullard/firehose

v1.0.0 2018-11-21 19:10 UTC

This package is auto-updated.

Last update: 2024-09-22 09:13:34 UTC


README

Maintainability Test Coverage

PHP反射类辅助器,用于直接在类中实例化、修改和提取数据。

安装

git clone git@github.com:aaronbullard/firehose.git

Composer

安装PHP Composer

composer require aaronbullard/firehose

测试

composer test

使用

Firehose/Hydrator使用PHP反射来绕过受保护的私有属性限制。

当尝试使用映射模式从数据库查询中实例化对象时,这可能很有用。此方法还允许您绕过构造函数中的任何验证约束。

尝试持久化对象时,无需贫血的getter。实例属性可以作为键值对提取以实现数据库持久化。

示例

给定Foo

class Foo
{
    private $bar;
    protected $baz;
    private $qux;

    public function __construct($bar, $baz = null, $qux = null)
    {
        $this->bar = $bar;
        $this->baz = $baz;
        $this->qux = $qux;
    }

    public function bar(){ return $this->bar; }
    public function baz(){ return $this->baz; }
}

创建一个新实例

use Firehose\Hydrator;

$foo = Hydrator::newInstance(Foo::class, [
    'bar' => 'bar',
    'baz' => 'baz'
]);

$this->assertInstanceOf(Foo::class, $foo);
$this->assertEquals('bar', $foo->bar());
$this->assertEquals('baz', $foo->baz());

修改现有实例

$foo = new Foo('bar', 'baz');

Hydrator::mutate($foo, [
    'bar' => 'newBar'
]);

$this->assertEquals('newBar', $foo->bar());

提取数据

$foo = new Foo('bar', 'baz', 'qux');

$data = Hydrator::extract($foo, ['bar', 'baz', 'qux']);

$this->assertEquals('bar', $data['bar']);
$this->assertEquals('baz', $data['baz']);
$this->assertEquals('qux', $data['qux']);

更多示例,请参阅测试:tests\HydratorTest.php