Created
April 30, 2024 18:58
-
-
Save graceman9/4335154c2a25d1c3de67a88bcf522cbf to your computer and use it in GitHub Desktop.
DDD VO basic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Usage example: | |
$product1 = new Product("Sample Product", 10.99, "Blue"); | |
$product2 = new Product("Sample Product", 10.99, "Blue"); | |
// Validate product | |
if ($product1->isValid()) { | |
echo "Product is valid.\n"; | |
} else { | |
echo "Product is not valid.\n"; | |
} | |
// Compare products | |
if ($product1->equals($product2)) { | |
echo "Products are equal.\n"; | |
} else { | |
echo "Products are not equal.\n"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Product | |
{ | |
public function __construct( | |
private string $name, | |
private float $price, | |
private string $color, | |
) { | |
} | |
public function getName(): string | |
{ | |
return $this->name; | |
} | |
public function getPrice(): float | |
{ | |
return $this->price; | |
} | |
public function getColor(): string | |
{ | |
return $this->color; | |
} | |
// Validation method | |
public function isValid(): bool | |
{ | |
// Basic validation, ensure non-empty name and positive price, weight, and length | |
return !empty($this->name) && $this->price > 0; | |
} | |
// Equality comparison method | |
public function equals(Product $otherProduct): bool | |
{ | |
return $this->name === $otherProduct->getName() | |
&& $this->price === $otherProduct->getPrice() | |
&& $this->color === $otherProduct->getColor(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I leave this gist here just for educational purposes. But this is NOT an Value Object.
The good news is that I can learn:
https://dev.to/ianrodrigues/writing-value-objects-in-php-4acg