The core library has no dependencies on other libraries. Plugins have dependencies on their specific libraries.
Install with composer:
composer require pauci/cqrs
final class User extends \CQRS\Domain\Model\AbstractEventSourcedAggregateRoot
{
private int $id;
private string $name;
public static function create(int $id, string $name): self
{
$user = new self($id);
$user->apply(new UserCreated($name));
return $user;
}
private function __construct(int $id)
{
$this->id = $id;
}
protected function applyUserCreated(UserCreated $event): void
{
$this->name = $event->getName();
}
public function getId(): int
{
return $this->id;
}
public function changeName(string $name): void
{
if ($name !== $this->name) {
$this->apply(new UserNameChanged($name));
}
}
protected function applyUserNameChanged(UserNameChanged $event): void
{
$this->name = $event->getName();
}
}
final class UserCreated
{
private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
final class ChangeUserName
{
public int $id;
public string $name;
}
final class UserNameChanged
{
private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
class UserService
{
protected $repository;
public function __construct($repository)
{
$this->repository = $repository;
}
public function changeUserName(ChangeUserName $command): void
{
$user = $this->repository->find($command->id);
$user->changeName($command->name);
}
}
class EchoEventListener
{
public function onUserNameChanged(
UserNameChanged $event,
\CQRS\Domain\Message\Metadata $metadata,
\DateTimeInterface $timestamp,
int $sequenceNumber,
int $userId
): void {
echo "Name of user #{$userId} changed to {$event->getName()}.\n";
}
}
$command = new ChangeUserName([
'id' => 1,
'name' => 'Jozko Mrkvicka',
]);
$commandBus->dispatch($command);