dddshelf / ddd-in-php-book-issues

Leave your comments, improvements or book mistakes as an issue! Thanks ❤️
https://leanpub.com/ddd-in-php
28 stars 2 forks source link

Should the record method not contain a call to the apply method? #66

Open MetalArend opened 7 years ago

MetalArend commented 7 years ago

On page 24, there is a recordApplyAndPublishThat method mentioned, that calls the recordThat method and the applyThat method. Should the recordThat method not simply call the applyThat method? Or is there a reason to ever record an event without applying the changes on the aggregate?

bertramakers commented 7 years ago

Major frameworks like Prooph and Broadway do it as described by @MetalArend : the method for recording an event directly calls the method for updating the internal state.

Broadway: https://github.com/qandidate-labs/broadway/blob/master/src/Broadway/EventSourcing/EventSourcedAggregateRoot.php#L31-L47

apply() records the event, and calls handleRecursively which then calls the handler which updates the aggregate's internal state.

Prooph: https://github.com/prooph/event-sourcing/blob/master/src/AggregateRoot.php#L79-L91

record() records the event, and calls apply() which then calls the method that updates the aggregate's internal state.

Buttercup.Protects: A reference/example library by Mathias Verraes, also does it like that in the example here: http://buttercup-php.github.io/protects/06-IsEventSourced.html

recordThat() records the event, and calls when() which then calls the method that updates the aggregate's internal state.

I'm also wondering why the aggregate in the book has a publish() method. Both Broadway and Prooph delegate publishing/dispatching of events to the persistence layer (repository or event store class) by injecting a publisher there, because it reduces the risk that an event would not be persisted because of concurrency issues but still be published to the event bus (which would result in incorrect read models being created).

Broadway: https://github.com/qandidate-labs/broadway/blob/master/src/Broadway/EventSourcing/EventSourcingRepository.php#L82-L83

Prooph: https://github.com/prooph/event-store-bus-bridge/blob/master/src/EventPublisher.php (Listens to the commit.post event on the EventStore which contains all newly appended events, and then dispatches them to an event bus)