eppak/value

值对象助手

1.0.0.0 2018-01-02 11:06 UTC

This package is auto-updated.

Last update: 2024-09-16 23:02:30 UTC


README

这是一个智能DTO对象,用于传输和处理数据。通常,值对象有一系列代表数据的属性getter和setter。

安装

# composer install eppak/value

构造函数

可以以各种模式创建,通常接受一个包含值的字段数组;第二个可选参数表示属性是否可写或只读。

  • 作为新对象。
  • 从数组。
  • 从JSON。

如果对象需要只读,可以使用 roValue 对象而不是 Value

初始化示例

<?php
    use eppak\value;
    
    //...
    
    $data = [ 'testRead' => 'read',
              'testWrite' => 'write',
              'testReadWrite' => 'readwrite',
              'undisciplined' => 'readwrite' ];
    
    $value = new Value( $data );
    $value = new Value( $data, [ 'testRead' => static::R,
                                 'testWrite' => static::W,
                                 'testReadWrite' => static::RW ] );    

    $value = Value::fromArray( $data );
    $value = Value::fromJson( '{"test": "read"}' );

读写示例

<?php
    $testRead =  $value->getTestRead();
    $testReadWrite =  $value->getTestReadWrite();
    
    $value->setTestReadWrite('some value');
    $value->setTestRead('some value'); // Thrown an error, is read only    

测试属性存在性

属性存在性可以是简单级别或多级,当值对象从JSON实例化时很有用。

<?php
    $json = Json::fromJson('{ "test": { "test1" : { "test2": { "test3" : 1} } }}');
    $testRead_present = $json->has('test');
    $testChin_present = $json->hasChain('test', 'test1>test2>test3');

速查表

许可证

MIT