Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active July 23, 2020 12:47
Show Gist options
  • Save webdevilopers/74c1f109c0f095ab65f7eef1f56a10f1 to your computer and use it in GitHub Desktop.
Save webdevilopers/74c1f109c0f095ab65f7eef1f56a10f1 to your computer and use it in GitHub Desktop.
Applying domain events to aggregate roots when deserializing payload of old events break current value object constraint changes
<?php
/**
* All characater were allowed in the initial value object.
*/
final class FirstName_V1
{
/** @var string $name */
private $name;
private function __construct(string $aName)
{
$name = NameNormalizer::withString($aName);
$this->name = $name;
}
public static function fromString(string $name): FirstName
{
return new self($name);
}
public function toString(): string
{
return $this->name;
}
}
/**
* Character e.g. numbers were forbidden.
*/
final class FirstName_V2
{
/** @var string $name */
private $name;
private function __construct(string $aName)
{
$name = NameNormalizer::withString($aName);
if (!NamePolicy::isSatisfiedBy($name)) {
throw new NameContainsIllegalCharacters();
}
$this->name = $name;
}
public static function fromString(string $name): FirstName
{
return new self($name);
}
public function toString(): string
{
return $this->name;
}
}
<?php
final class NameChanged extends AggregateChanged
{
/** @var PersonId */
private $personId;
/** @var FirstName */
private $firstName;
public static function with(PersonId $personId, FirstName $oldFirstName, FirstName $newFirstName): NameChanged
{
$event = self::occur(
$personId->toString(),
[
'personId' => $personId->toString(),
'oldFirstName' => $oldFirstName->toString(),
'newFirstName' => $newFirstName->toString(),
]
);
$event->personId = $personId;
$event->oldFirstName = $oldFirstName;
$event->newFirstName = $newFirstName;
return $event;
}
public function personId(): PersonId
{
if (null === $this->personId) {
$this->personId = PersonId::fromString($this->aggregateId());
}
return $this->personId;
}
public function newFirstName(): FirstName
{
if (null === $this->newFirstName) {
$this->newFirstName = FirstName::fromString($this->payload['newFirstName']);
}
return $this->newFirstName;
}
}
<?php
final class Person extends AggregateRoot
{
/** @var PersonId */
private $personId;
/** @var FirstName */
private $firstName;
public function changeName(FirstName $newName): void
{
if ($newName->equalsTo($this-firstName)) {
return;
}
$this->recordThat(NameChanged::with($this->personId, $this->firstName, $newName));
}
protected function apply(AggregateChanged $event): void
{
switch (get_class($event)) {
case NameChanged::class:
/** @var NameChanged $event */
$this->firstName = $event->newFirstName();
break;
}
}
}
@webdevilopers
Copy link
Author

Discussion moved to:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment