Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the Domain Event pattern

I've been attempting to implement this pattern in a new project as described by udi dahan.

I like the idea of if but I'm not quite sure yet in what cases it should be applied for (new to this stuff...).

For example lets say I have an event OnUserCreated. I want one of the handlers to send a confirmation email to the user. But what if the event get fired the email gets sent and then there is an error committing the transaction and the data never gets saved to the database. Is the pattern applicable in this situation? I've read people say no but some projects I've gone over do in fact do it like that. Or is this something I should only be using to load and update other entities...on the other hand I read someone say that the associated entities needed for the operation should already be loaded so I should not be loading them from the database in an event.

like image 687
maciek Avatar asked Apr 21 '11 19:04

maciek


1 Answers

It of course depends on how you choose to implement your system.

You can consider multiple options here:

1. Two-phase commit When doing a two-phase commit, basically every handler contains 3 methods: one to Prepare, one to Commit and one to Roll Back.

For all event handlers, the Prepare is called first. If none of those reports a problem, then all the handlers' Commit() methods are called. If any of those reports a problem -- despite no issues being reported by the Prepare() calls -- then for all the handlers whose Commit() has already been executed, you call their Rollback() methods.

2. Internal and External event handlers Another option is to make a separation of event handlers. You may publish an event, such as UserCreated, which is processed by event handlers that take part in the transaction first. The event gets stored in the DB as part of the transaction. Then you can have external event handlers which react only to events that are already stored in the DB -- such as your email sender. These can only get called after the initial transaction is committed.

I'm sure you can think of more ways to handle your specific scenario.

like image 159
Roy Dictus Avatar answered Oct 04 '22 12:10

Roy Dictus