Immutable Value Objects for PHP
composer require phpgears/value-object
Require composer autoload file
require'./vendor/autoload.php';Extend from Gears\ValueObject\AbstractValueObject. Make your class final, value objects should always be final
Be aware of the protected constructor, you should create a "named constructor" for your value object
useGears\ValueObject\AbstractValueObject;
finalclass CustomStringValueObject extends AbstractValueObject
{
private$value;
publicstaticfunctionfromString(string$value)
{
$stringObject = newself();
$stringObject->value = $value;
return$stringObject;
}
publicfunctiongetValue(): string
{
return$this->value;
}
publicfunctionisEqualTo($valueObject): bool
{
return\get_class($valueObject) === self::class && $valueObject->getValue() === $this->value;
}
}Extending AbstractValueObject does not automatically define serialization mechanisms in your value objects because value objects can be composed of several values, other value objects and even other objects such as enums
For this consider adding serialization methods in your value objects to control how serialization takes place
useGears\ValueObject\AbstractValueObject;
finalclass Money extends AbstractValueObject implements \Serializable
{
privateconstCURRENCY_EUR = 'eur';
private$value;
private$precision;
private$currency;
publicstaticfunctionfromEuro(int$value, int$precision)
{
$money = newself();
$money->value = $value;
$money->precision = $precision;
$money->currency = static::CURRENCY_EUR; // Should be an enumreturn$money;
}
// [...]finalpublicfunction__serialize(): array
{
return [
'value' => $this->value,
'precision' => $this->precision,
'currency' => $this->currency,
];
}
finalpublicfunction__unserialize(array$data): void
{
$this->assertImmutable();
$this->value = $data['value'];
$this->precision = $data['precision'];
$this->currency = $data['currency'];
}
finalpublicfunctionserialize(): string
{
returnserialize([
$this->value,
$this->precision,
$this->currency,
]);
}
publicfunctionunserialize($serialized): void {
$this->assertImmutable();
list(
$this->value,
$this->precision,
$this->currency
) = \unserialize($serialized, ['allowed_classes' => false]);
}
}Enums and Value Objects get along perfectly, consider using phpgears/enum for enumerations
Found a bug or have a feature request? Please open a new issue. Have a look at existing issues before.
See file CONTRIBUTING.md
See file LICENSE included with the source code for a copy of the license terms.