tleckie / value-object
PHP value-object. Library to implement value-object / nullable-value-object in PHP
Fund package maintenance!
teodoroleckie
www.paypal.com/donate?business=ZHYA2MTGA4884¤cy_code=USD
Requires
- php: ^8
Requires (Dev)
- friendsofphp/php-cs-fixer: v3.0.0-beta.2
- infection/infection: ^0.21.5
- phpunit/phpunit: ^9.5
README
Create your own value-object type:
You should only extend from the ValueObject class
<?php /** * Class Age */ class Age extends ValueObject { }
Compare value-objects:
<?php /** * Class Age */ class Age extends ValueObject { } $john = new Age(34); $mario = new Age(34); $raquel = new Age("34"); $john->equals($mario); // true $john->equals($raquel); // false $john->equals(new FirstName('Mario')); // false $raquel->value(); // "34"
Force primitive type:
Override value() method to indicate the return primitive type.
<?php /** * Class Age */ class Age extends ValueObject { /** * @return int */ public function value(): int { return parent::value(); } } $raquel = new Age("34"); $mario = new Age(34); $raquel->value(); // int 34 $mario->equals($raquel); // true (string)$mario; // string "34"
Nullable value-object
If your object can contain null value you can extend of NullableValueObject class
<?php /** * Class Age */ class Age extends NullableValueObject { } // That's all! I hope this helps you