Пример #1
0
 /**
  * @param AggregateHistory $aggregateHistory
  * @return RecordsEvents
  */
 public static function reconstituteFrom(AggregateHistory $aggregateHistory)
 {
     // `AggregateHistory` is a list of chronological `DomainEvents` for a single Aggregate instance. Let's start by
     // fetching its identifier.
     $basketId = $aggregateHistory->getAggregateId();
     // We instantiate the Basket object. (As you recall, the constructor is private.)
     $basket = new BasketV4(new BasketId($basketId));
     foreach ($aggregateHistory as $event) {
         // As you saw earlier, our Aggregate keeps state, to protect invariants. We need to rebuild this state from
         // the events in the `AggregateHistory`. But there's a problem: we can't call methods like `pickUp()`,
         // `addProduct()`, and `removeProduct()`, because these would call `recordThat()`. That would cause the
         // events to be recorded a second time.
         // The trick is to separate the logic that applies events to the state. We'll call a new private method:
         $basket->when($event);
     }
     // Finally we return the newly reconstituted Basket.
     return $basket;
 }