Setting Up DomainEventListeners

Where's the best place to set up the subscribers to the DomainEventPublisher? It depends. For global subscribers that will potentially affect the entire request cycle, the best place might be on the DomainEventPublisher initialization itself. For subscribers affected by a specific Application Service, the service instantiation might be a better place. Let's see an example using Silex.

In Silex, the best way to register a Domain Event Publisher that will persist all Domain Events is by using an Application Middleware. According to the Silex 2.0 Documentation:

A before application middleware allows you to tweak the Request before the controller is executed.

This is the correct place to subscribe the listener responsible for persisting to the database those Events that will be sent to RabbitMQ later:

// ...
$app['em'] = $app-> share(function () {
return (new EntityManagerFactory())->build();
});

$app['event_repository'] = $app->share(function ($app) {
return $app['em']->getRepository(
'DddDomainModelEventStoredEvent'
);
});

$app['event_publisher'] = $app->share(function($app) {
return DomainEventPublisher::instance();
});

$app->before(
function(SymfonyComponentHttpFoundationRequest $request)
use($app) {

$app['event_publisher']->subscribe(
new PersistDomainEventSubscriber(
$app['event_repository']
)
);
}
);

With this setup, each time an Aggregate publishes a Domain Event, it will get persisted into the database. Mission accomplished.

Exercise
If you're working with Symfony, Laravel, or another PHP framework, find a way to subscribe globally specific subscribers for performing tasks around your Domain Events.

In case you want to perform any action on all Domain Events when the request is about to finish, you can create a Listener that will store all published Domain Events in memory. If you add a getter to that Listener to return all Domain Events, you can then decide what to do. This can be useful if you don't want to or if you can't persist the Events in the same transaction, as suggested before.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset