flancer32/php_data_object

简化数据容器(受Varien_Object启发)。

0.2.2 2018-01-21 07:41 UTC

This package is auto-updated.

Last update: 2024-09-15 23:47:05 UTC


README

Build Status codecov.io

"智能数据结构加笨拙的代码要比反过来好很多。" (c) Eric S. Raymond

"差的程序员担心代码。好的程序员担心数据结构和它们之间的关系。" (c) Linus Torvalds

概述

这是另一个PHP数据容器实现(类似于DTO / SDO),类似于关联数组的某种包装器。这个实现的主要目标是作为原始数据的访问器。

原生PHP对象

结构

我们可以使用任何PHP对象的任何属性

$obj1 = new class {};
$obj2 = new class {};
$obj1->name = 'first';
$obj2->code = 'OBJ2';
$obj1->sub = $obj2;
$this->assertEquals('first', $obj1->name);
$this->assertEquals('OBJ2', $obj1->sub->code);

更多...

路径

我们可以以PHP风格设置/获取内部属性的值

$obj->sub->code = $code;
$code = $obj->sub->code;

但是,如果$obj->sub属性不存在,我们将得到"未定义属性"错误。

类型检查

我们需要使用访问器来控制属性类型。

这是具有string属性的Customer

/**
 * @property string $name Customer name.
 */
class Customer
{
    public function getName() : string
    {
        return $this->name;
    }

    public function setName(string $data)
    {
        $this->name = $data;
    }
}

这是具有Customer属性的Order

/**
 * @property Customer $customer
 */
class Order
{
    public function getCustomer() : Customer
    {
        return $this->customer;
    }

    public function setCustomer(Customer $data)
    {
        $this->customer = $data;
    }
}

这是没有错误的代码(所有类型都是预期的)

$customer = new Customer();
$customer->setName('John Dow');
$order = new Order();
$order->setCustomer($customer);
$this->assertTrue(is_string($order->getCustomer()->getName()));

此代码将抛出\TypeError异常

$customer = new class {};
$customer->name = 'John Dow';
$order = new Order();
$order->setCustomer($customer);

更多...

数据对象

结构

路径

使用路径,如果属性链存在,则将具有属性值,否则为null

$code = $obj->get('sub/code');
$code = $obj->get('/sub/code');    // equals to 'sub/code'
$code = $obj->get('/subs/0/code'); // 'subs' is array
$code = $obj->get('/sub/code/does/not/exist'); // 'null' is returned, no error is occured

我们还可以通过路径设置数据属性

$obj->set('order/customer/name', 'John Dow');

类型提示

安装

添加到composer.json

"require": {
    "flancer32/php_data_object": "0.1.0"
}

开发

$ composer install
$ ./vendor/bin/phpunit -c ./test/unit/phpunit.dist.xml