Skip to content

Instantly share code, notes, and snippets.

@graceman9
Created April 30, 2024 18:58
Show Gist options
  • Save graceman9/4335154c2a25d1c3de67a88bcf522cbf to your computer and use it in GitHub Desktop.
Save graceman9/4335154c2a25d1c3de67a88bcf522cbf to your computer and use it in GitHub Desktop.
DDD VO basic example
<?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";
}
<?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();
}
}
@graceman9
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment