We'll explore Chapter 6, Domain-Events in future chapters; however, it's important to highlight that operations performed on Entities can fire Domain Events. This approach is used to communicate the Domain change to other parts of the Application, or even to other Applications, as you'll see in Chapter 12, Integrating Bounded Contexts:
class Post
{
// ...
public function publish()
{
$this->setStatus(
Status::published()
);
$this->publishedAt(new DateTimeImmutable());
DomainEventPublisher::instance()->publish(
new PostPublished($this->id)
);
}
public function unpublish()
{
$this->setStatus(
Status::draft()
);
$this-> publishedAt = null;
DomainEventPublisher::instance()->publish(
new PostUnpublished($this->id)
);
}
// ...
}
Domain Events can even be fired when a new instance of our Entity is created:
class User
{
// ...
public function __construct(UserId $userId, $email, $password)
{
$this->setUserId($userId);
$this->setEmail($email);
$this->setPassword($password);
DomainEventPublisher::instance()->publish(
new UserRegistered($this->userId)
);
}
}