diff --git a/README.md b/README.md index 1e8d87a6..b3d06b5c 100644 --- a/README.md +++ b/README.md @@ -8,3 +8,184 @@ Small lightweight event-sourcing library. composer require patchlevel/event-sourcing ``` +## define aggregate + +```php + */ + private array $messages; + + private function __construct() + { + } + + public function email(): Email + { + return $this->email; + } + + /** + * @return array + */ + public function messages(): array + { + return $this->messages; + } + + public static function createProfile(ProfileId $id, Email $email): self + { + $self = new self(); + $self->apply(ProfileCreated::raise($id, $email)); + + return $self; + } + + public function publishMessage(Message $message): void + { + $this->apply(MessagePublished::raise( + $this->id, + $message, + )); + } + + protected function applyProfileCreated(ProfileCreated $event): void + { + $this->id = $event->profileId(); + $this->email = $event->email(); + $this->messages = []; + } + + protected function applyMessagePublished(MessagePublished $event): void + { + $this->messages[] = $event->message(); + } + + public function aggregateRootId(): string + { + return $this->id->toString(); + } +} +``` + +## define events + +```php +toString(), + [ + 'profileId' => $id->toString(), + 'email' => $email->toString(), + ] + ); + } + + public function profileId(): ProfileId + { + return ProfileId::fromString($this->aggregateId); + } + + public function email(): Email + { + return Email::fromString($this->payload['email']); + } +} +``` + +# define projection + +```php +db = $db; + } + + public static function getHandledMessages(): iterable + { + yield MessagePublished::class => 'applyMessagePublished'; + } + + public function applyMessagePublished(MessagePublished $event): void + { + $message = $event->message(); + + $this->db->collection('message')->insertOne([ + '_id' => $message->id()->toString(), + 'profile_id' => $event->profileId()->toString(), + 'text' => $message->text(), + 'created_at' => $message->createdAt()->format(DATE_ATOM), + ]); + } + + public function drop(): void + { + $this->db->collection('message')->drop(); + } +} +``` + +## usage + +```php +profileRepository = $profileRepository; + } + + public function __invoke(CreateProfile $command): void + { + $profile = Profile::createProfile($command->profileId(), $command->email()); + + $this->profileRepository->store($profile); + } +} +```