PHP code example of yomy / valueobject

1. Go to this page and download the library: Download yomy/valueobject library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yomy / valueobject example snippets


use YomY\ValueObject\ValueObject;
$object = ValueObject::instance(1);

$value = $object->getValue();

$object1 = ValueObject::instance(1);
$object2 = ValueObject::instance(1);
//These two are the same objects ($object1 === $object2)

public function doSomething(ValueObject $valueObject) {
    $value = $valueObject->getValue();
    ...
}

class UserId extends ValueObject {}
class DataId extends ValueObject {}
...
public function doSomething(UserId $userId, DataId $dataId) {
    ...
}

$object1 = ValueObject::instance('');
$object2 = ValueObject::instance(null);
$object3 = ValueObject::instance(false);
$object4 = ExtendedValueObject::instance('');
$object5 = ExtendedValueObject::instance(null);
$object6 = ExtendedValueObject::instance(false);
//All of the above are different

$object1 = ValueObject::instance(1);
$object2 = ValueObject::instance(1);
$same = $object1->equals($object2); //true

class MyWeakObject extends ValueObject {
    use WeakValueObjectTrait;
}
...
$weakObject1 = MyWeakObject::instance(1);
$serializedWeakObject = serialize($weakObject1);
$weakObject2 = unserialize($serializedWeakObject);
//These two objects are "equal" but not the same
$weakObject1->equals($weakObject2); //true
//On regular value objects this would be false

use YomY\ValueObject\EnumValueObject;
class Category extends EnumValueObject {
    const FIRST = 1;
    const SECOND = 2;
    const THIRD = 3;
}

$category = Category::instance(Category::FIRST);

$category = Category::FIRST();

$category = Category::instance('missing_value');
$category = Category::MISSING();

use YomY\ValueObject\PositiveIntValueObject;
$object1 = PositiveIntValueObject::instance(1);
$object2 = PositiveIntValueObject::instance('1');
//These two are the same objects ($object1 === $object2)

$object = PositiveIntValueObject::instance(0);
$object = PositiveIntValueObject::instance('0');

class UserId extends PositiveIntValueObject {}
class DataId extends PositiveIntValueObject {}
$user = UserId::instance(42);
$data = DataId::instance(42);
//these two are not the same