david-garcia/value-object

用于处理值对象并防止原始对象偏执的坏习惯的库

0.2.0 2021-02-11 08:15 UTC

This package is auto-updated.

Last update: 2024-09-11 16:19:38 UTC


README

用于处理值对象并防止原始对象偏执的坏习惯的库

Latest Version Build Status Code Coverage Quality Score Total Downloads

变更日志

本项目所有显著变更都将记录在 此变更日志文件 中。

安装

使用Composer要求供应商

composer require david-garcia/value-object

用法

确保您正在加载Composer的自动加载

require 'vendor/autoload.php';

别忘了为每个需要使用的值对象添加use声明

// Example for StringValue
use DavidGarcia\ValueObject\Primitive\StringValue;

所有值对象都有一个静态的 create() 方法

StringValue::create('qwerty');

第一个参数是要被值对象包装的值。第二个参数允许您 静态缓存 值对象,因此您可以两次实例化具有相同值的对象,但系统只会创建一次

$stringValue1 = StringValue::create('qwerty', true);
$stringValue2 = StringValue::create('qwerty', true);

if ($stringValue1 === $stringValue2) {
    // TRUE
    // It's the same object, so it goes inside this conditional
}

$stringValue3 = StringValue::create('qwerty');
$stringValue4 = StringValue::create('qwerty');

if ($stringValue3 === $stringValue4) {
    // FALSE
    // Although they have the same value, the system has created two different objects
}

Null值始终持有 null

// `NullValue` does not expect any argument
$nullValue = NullValue::create();

所有值对象都有一个 getValue() 方法来公开值

$stringValue = StringValue::create('qwerty');
$stringValue->getValue(); // Returns 'qwerty'

StringValue 值对象以及从该对象扩展的任何其他对象都可以使用 __toString 魔法方法来返回字符串值,作为对 getValue() 方法的替代

$stringValue = StringValue::create('qwerty');
(string) $stringValue; // Returns 'qwerty'

所有值对象(除 NullValue 之外)都有一个 equals() 方法,用于比较相同类型的两个值对象的内容

$stringValue1 = StringValue::create('qwerty', true);
$stringValue2 = StringValue::create('qwerty', true);

if ($stringValue1->equals($stringValue2)) {
    // TRUE
    // We ignore the fact that is a cached object, as we compare the value
}

$stringValue3 = StringValue::create('qwerty');
$stringValue4 = StringValue::create('qwerty');

if ($stringValue3->equals($stringValue4)) {
    // TRUE
    // We have a match for the values, so even if we handle two different objects,
    // their values are equal
}