The Aggregate pattern is an important part of Domain Driven Design. It prevents inconsistencies and is responsible for enforcing business rules within a collection of objects. For these reasons alone, it is clear to see why it is a key component of a domain model.

Architectural advice recommends that the layer containing the Domain Model be independent from infrastructural concerns. While this is good advice, the Active Record pattern on the other hand wraps a row in the database. Because of this, it is almost impossible to decouple from the persistence layer.

Mixing persistence concerns into a Domain Model can become complex and lead to a lot of bad decisions. This does not mean that it is impossible to create an Active Record Domain Model. In this article, we will work through an example of building an Aggregate which also extends Eloquent: a popular Active Record ORM.

What is an Aggregate?

An Aggregate is a collection of objects which act as a single unit – with one of these objects acting as the Aggregate’s Root. Interaction from outside of the Aggregate must only communicate through the Root object. Aggregate Roots can then manage the consistency of all the objects within its boundary.

A set of elements joined into one

Boundaries for Aggregates define the scope of a transaction. Before the transaction can be committed, manipulation to the cluster of objects must comply with the business rules. Only one Aggregate can be committed within a single transaction. Any changes required to additional Aggregates must be eventually consistent, happening within another transaction.

In his book, Implementing Domain-Driven Design, Vaughn Vernon outlines a set of guidelines in which he calls: “the rules of Aggregate design”:

  1. Protect True Invariants in Consistency Boundaries
  2. Design Small Aggregates
  3. Reference Other Aggregates Only By Identity
  4. Use Eventual Consistency Outside the Consistency Boundary

Continue reading %Modeling an Aggregate with Eloquent%

Source: SitePoint