How the Domain Event Publisher Works

A Domain Event Publisher is a Singleton class available from our Bounded Context needed to publish Domain Events. It also has support to attach listeners — Domain Event Subscribers — that will be listening for any Domain Event they're interested in. This isn't much different from subscribing to an Event with jQuery using the on method:

class DomainEventPublisher
{
private $subscribers;
private static $instance = null;

public static function instance()
{
if (null === static::$instance) {
static::$instance = new static();
}

return static::$instance;
}

private function __construct()
{
$this->subscribers = [];
}

public function __clone()
{
throw new BadMethodCallException('Clone is not supported');
}

public function subscribe(
DomainEventSubscriber $aDomainEventSubscriber
) {
$this->subscribers[] = $aDomainEventSubscriber;
}

public function publish(DomainEvent $anEvent)
{
foreach ($this->subscribers as $aSubscriber) {
if ($aSubscriber->isSubscribedTo($anEvent)) {
$aSubscriber->handle($anEvent);
}
}
}
}

The publish method goes through all the possible subscribers, checking if they're interested in the published Domain Event. If that's the case, the handle method of the subscriber is called.

The subscribe method adds a new DomainEventSubscriber that will be listening to specific Domain Event types:

interface DomainEventSubscriber
{
/**
* @param DomainEvent $aDomainEvent
*/
public function handle($aDomainEvent);

/**
* @param DomainEvent $aDomainEvent
* @return bool
*/
public function isSubscribedTo($aDomainEvent);
}

As we've already discussed, persisting all the Domain Events is a great idea. We can easily persist all the Domain Events published in our app by using a specific subscriber. Let's create a DomainEventSubscriber that will listen to all Domain Events, no matter what type, and persist them using our EventStore:

class PersistDomainEventSubscriber implements DomainEventSubscriber
{
private $eventStore;

public function __construct(EventStore $anEventStore)
{
$this->eventStore = $anEventStore;
}

public function handle($aDomainEvent)
{
$this->eventStore->append($aDomainEvent);
}

public function isSubscribedTo($aDomainEvent)
{
return true;
}
}

$eventStore could be a custom Doctrine Repository, as already seen, or any other object capable of persisting DomainEvents into a database.

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

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