PHP Value Objects
GPL-2.0 License
A generic set of PHP Value Objects for use in any project.
When people exchange business cards, they generally do not distinguish between each unique card; they only are concerned about the information printed on the card. In this context, business cards are value objects.
composer require best-served-cold/phalue-objects
To make this code consistent, we've stuck to a certain set of restrictions:
Disclaimer: This is my interpretation of "The rules".
The value object's value must be set at the time of construction. At no point should the value be mutated within the object.
The value object can only be constructed from one value, this can be any of the following types:
Rather than mutating, a new object can be instantiated from an existing one.
Example:
//...
public function double()
{
return new static($this->getValue() * 2);
}
...//
Instead of an object having multiple object properties, it should be created from multiple arguments.
Example:
//...
public static function fromVars($one = 1, $two = 2, $three = 3)
{
return new static([$one, $two, $three]);
}
...//
The type of a value object is irrelevant to equality:
Example:
//...
$bob = $stringValueObject->equals($csvValueObject);
...//
$bob
is true where the type and value are equal.
Value objects must not persist data between run times. For example: no database or session information should be collected from within the object.
Follow PSR-FIG rules.
Example:
new SomeClass('value');
Example:
SomeClass::fromSomeObject($someObject);
Example:
$someObject->toArray();