Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?php
// One refactoring would be to gather most of this behavior in a Domain Event collection class.
// This could contain more of the behaviors we'd use in the trait. This is probably better and
// could encapsulate other behaviors like playheads neatly but it doesn't change the fact you
// still end up wanting a public method or a couple of protected helper functions duplicated.
// This is a simplified example, admittedly. Add in a couple extra properties or conditions and
// the desire for more leverage grows.
// At the same time, it also demonstrates how adding an abstraction (the DomainEventStream)
// inherently offers some additional leverage, though it doesn't completely solve the issue.
class DomainEventStream
{
private $events = [];
public function __construct($events = [])
{
$this->events = [];
}
public function raise($event)
{
$this->events[] = $event;
}
public function releaseAndResetEvents()
{
$pendingEvents = $this->events;
$this->events = [];
return new static($pendingEvents);
}
}
class MyEntity
{
private $eventStream;
public function __construct()
{
// we could also do this lazily on a protected raise or release but that'd just
// increase the boiler plate and thus the desire for a trait any more.
$this->eventStream = new DomainEventStream();
}
public function releaseEvents() // still have to put this on every entity
{
return $this->eventStream->releaseAndResetEvents();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment