Proper reconstitution of Aggregate objects in the Repository?
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.
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).
精彩评论