Objects Vs. Primitive Types

Most of the time, the Identity of an Entity is represented as a primitive type — usually a string or an integer. But using a Value Object to represent it has more advantages:

  • Value Objects are immutable, so they can't be modified.
  • Value Objects are complex types that can have custom behaviors, something which primitive types can't have. Take, as an example, the equality operation. With Value Objects, equality operations can be modeled and encapsulated in their own classes, making concepts go from implicit to explicit.

Let's see a possible implementation for OrderId, the Order Identity that has evolved into a Value Object:

namespace DddBillingDomainModel;

class OrderId
{
private $id;

public function __construct($anId)
{
$this->id = $anId;
}

public function id()
{
return $this->id;
}

public function equalsTo(OrderId $anOrderId)
{
return $anOrderId->id === $this->id;
}
}

There are different implementations you can consider for implementing the OrderId. The example shown above is quite simple. As explained in the Chapter 3, Value Objects, you can make the __constructor method private and use static factory methods to create new instances. Talk with your team, experiment, and agree. Because Entity Identities are not complex Value Objects, our recommendation is that you shouldn't worry too much here.

Going back to the Order, it's time to update references to OrderId:

 class Order
{
private $id;
private $amount;
private $firstName;
private $lastName;

public function __construct(
OrderId $anOrderId, Amount $amount, $aFirstName, $aLastName
) {
$this->id = $anOrderId;
$this->amount = $amount;
$this->firstName = $aFirstName;
$this->lastName = $aLastName;
}

public function id()
{
return $this->id;
}

public function firstName()
{
return $this->firstName;
}

public function lastName()
{
return $this->lastName;
}

public function amount()
{
return $this->amount;
}
}

Our Entity has an Identity modeled using a Value Object. Let's consider different ways of creating an OrderId.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset