Factory Method on Aggregate Root

The Factory Method pattern, as defined in the classic, Gang of Four, is a creational pattern that:

Defines an interface for creating an object, but leaves the choice of its type to the subclasses, creation being deferred at run-time.

Adding a Factory Method in the Aggregate Root hides the internal implementation details of creating Aggregates from any external client. This also moves the responsibility for the integrity of the Aggregate back to the root.

In a Domain Model where we have a User Entity and a Wish Entity, the User acts as the Aggregate root. There's no Wish without User. The User Entity should manage its Aggregates.

The way to move the control of Wish back to the User Entity is by placing a Factory method in the Aggregate root:

class User
{
// ...

public function makeWish(WishId $wishId, $email, $content)
{
$wish = new WishEmail(
$wishId,
$this->id(),
$email,
$content
);

DomainEventPublisher::instance()->publish(
new WishMade($wishId)
);

return $wish;
}
}

The client doesn't need to know the internal details of how the Aggregate Root handles the creation logic:

 $wish = $aUser->makeWish(
$wishRepository->nextIdentity(),
'[email protected]',
'I want to be free!'
);
..................Content has been hidden....................

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