PHP code example of pauci / cqrs

1. Go to this page and download the library: Download pauci/cqrs library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pauci / cqrs example snippets



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);