0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

<?php
trait EventSourcedRootEntity
{
    /**
     * @var DomainEvent[]
     */
    private $mutatingEvents = [];
    
    public function apply(DomainEvent $event)
    {
        $this->mutatingEvents[] = $event;
        $this->mutateWhen($event);
    }
    
    private function mutateWhen(DomainEvent $domainEvent)
    {
        $eventType = (new \ReflectionClass($domainEvent))->getShortName();
        $mutatorMethodName = 'when'.$eventType;
        
        if (method_exists($this, $mutatorMethodName) === false) {
            throw new \RuntimeException(
                sprintf("Method %s() does not exist", $mutatorMethodName)
            );
        }
        
        try {
            $mutatorMethod = new \ReflectionMethod($this, $mutatorMethodName);
            $mutatorMethod->setAccessible(true);
            $mutatorMethod->invoke($this, $domainEvent);
        } catch (\ReflectionException $e) {
            throw new \RuntimeException(
                sprintf("Method %s() failed", $mutatorMethodName), null, $e
            );
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?