1
votes

Assuming that no ORM (e.g. Doctrine) is used inside the Repository, my question is what is the proper way of instantiating the Aggregate objects? Is it instantiating the child objects directly inside the Repository and just assign it to the Aggregate Root through its setters or the Aggregate Root is responsible of constructing its child entities/objects?

Example 1:

class UserRepository
{
  // Create user domain entity.
  $user = new User();
  $user->setName('Juan');

  // Create child object orders entity.
  $orders = new Orders($orders);
  $user->setOrders($orders);
}

Example 2:

class UserRepository
{
  // Create user domain entity.
  $user = new User();
  $user->setName('Juan');

  // Get orders.
  $orders = $ordersDao->findByUser(1);
  $user->setOrders($orders);
}

whereas in example 2, instantiation of orders are taken care inside the user entity.

1
I'm not really sure (don't fully understand the question) but the comment at the end that says "orders are taken care inside the user entity" - i think you don't want to be doing that. Entities don't want to be instating themselves. If you must delegate that type of responsibility from within an entity you should proxy it to a Domain Service. - Matt Kocaj

1 Answers

3
votes

You definitely should be using the constructor to create objects, not setters. One of the important principles of DDD is communicating intent. If name is required in order to create a user, then you communicate that requirement clearly by only allowing a User instance to be created if a name is supplied. These are called "invariants" and should always be satisfied before an object is created. This way you are clearly saying "this is what you need to supply before this object is in a valid state."

When reconstituting an object (e.g. in a repository), you'll want to pass the child objects into the constructor. In my experience, my aggregates have 2 constructors: one for creation (possibly called by a factory), and one for reconstitution (typically called by a repository).