Пример #1
0
use Buttercup\Protects\DomainEvents;
use Buttercup\Protects\IsEventSourced;
use Buttercup\Protects\RecordsEvents;
use Buttercup\Protects\Tests\Misc\ProductId;
use Buttercup\Protects\Tests\Misc\When;
$test = function () {
    $basketId = BasketId::generate();
    $basket = BasketV4::pickUp($basketId);
    $productId = new ProductId('TPB1');
    $basket->addProduct($productId, "The Princess Bride");
    $basket->addProduct(new ProductId('TPB2'), "The book");
    $basket->removeProduct($productId);
    $events = $basket->getRecordedEvents();
    $basket->clearRecordedEvents();
    // Here we would store the events, and later retrieve them from that store.
    $reconstitutedBasket = BasketV4::reconstituteFrom(new AggregateHistory($basketId, (array) $events));
    it("should be the same after reconstitution", $basket == $reconstitutedBasket);
};
// We declare that `Basket` `IsEventSourced`, in other words, that we can rebuild it from it's events.
final class BasketV4 implements RecordsEvents, IsEventSourced
{
    use When;
    // The `IsEventSourced` interface requires us to implement a `reconstituteFrom(AggregateHistory)` static method.
    // This method is like an alternative constructor. Recall that we had `pickUp()` earlier, which was the constructor
    // for calling the Basket into life. `Reconstitute` implies that this Basket already exists conceptually, but that
    // we suspended it temporarily by unloading it from memory. The difference is subtle but important.
    /**
     * @param AggregateHistory $aggregateHistory
     * @return RecordsEvents
     */
    public static function reconstituteFrom(AggregateHistory $aggregateHistory)