PHPackages                             cvek/domain-events - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cvek/domain-events

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

cvek/domain-events
==================

Component to add domain events feature

4.0.0(1y ago)24181MITPHPPHP ^7.4|^8.0

Since Feb 28Pushed 1y ago1 watchersCompare

[ Source](https://github.com/CvekCoding/DomainEvents)[ Packagist](https://packagist.org/packages/cvek/domain-events)[ RSS](/packages/cvek-domain-events/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (8)Versions (31)Used By (0)

Domain events bundle for Symfony
================================

[](#domain-events-bundle-for-symfony)

The bundle integrates with Symfony application to provide domain events support. This allows to be doctrine-agnostic and raise events during the business logic implementation.

Domain events are of three types:

- `preFlush`. Will be processed synchronously before persisting to DB;
- `onFlush`. Will be processed during persisting to DB (sync or async - see below);
- `postFlush`. Will be processed after persisting to DB (sync or async - see below).

To use this bundle implement `RaiseEventsInterface` interface in your entity class and create your custom domain events. We recommend you to use `RaiseEventsTrait` to simplify this even more.

Sync/Async messages
-------------------

[](#syncasync-messages)

Any domain event can be executed in a `sync` or an `async` way during `onFlush` and `postFlush` Doctrine events. Extend one of abstract classes: `AbstractSyncDomainEvent` or `AbstractAsyncDomainEvent` to have `sync` or `async` event respectively.

Async way is a very powerful approach and must be used in the following cases:

- you want to postpone some time-consuming or remote tasks;
- you want to avoid restrictions of Doctrine event system (e.g. see [this](https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/events.html#onflush) and [this](https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/events.html#postflush)).

Thanks to `db` transport with doctrine storage (will be created automatically) - all the async domain events will be routed and persisted to db automatically.

To consume them we recommend to use the following supervisor config:

```
[program:db]
command=/srv/api/bin/console messenger:consume db --memory-limit=128M --time-limit=3600 --limit=100
process_name=%(program_name)s_%(process_num)02d
numprocs=1
autostart=true
autorestart=true
startsecs=0
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0

```

⚠️ **Dont forget to add it to your application!**

Direct Async message
--------------------

[](#direct-async-message)

If you dont want to write your own async message handler, but dispatch your message directly, then simply extend `AbstractDirectAsyncDomainEvent` in your message and use it this way:

```
use Doctrine\ORM\Events;

public function setName(string $name): self
{
    $this->name = $name;
    $this->raise(new NameChangedDirectAsyncMessage($this));

    return $this;
}
```

The message will be dispatched directly to bus, without of need to write your own handler.

Example
-------

[](#example)

### Install

[](#install)

`composer req cvek/domain-events`

### Use

[](#use)

#### Create domain event

[](#create-domain-event)

##### Sync event

[](#sync-event)

```
use \Cvek\DomainEventsBundle\EventDispatch\Event\AbstractSyncDomainEvent;

final class FooNameChanged extends AbstractSyncDomainEvent
{
    private Foo $foo;
    private string $oldName;
    private string $newName;

    public function __construct(Foo $foo, string $oldName, string $newName)
    {
        $this->foo = $foo;
        $this->oldName = $oldName;
        $this->newName = $newName;
    }

    public function getFoo(): Foo
    {
        return $this->foo;
    }

    public function getOldName(): string
    {
        return $this->oldName;
    }

    public function getNewName(): string
    {
        return $this->newName;
    }

    public function isAsync() : bool
    {
        return false;
    }
}
```

##### Async event

[](#async-event)

```
use \Cvek\DomainEventsBundle\EventDispatch\Event\AbstractAsyncDomainEvent;

final class FooPasswordChanged extends AbstractAsyncDomainEvent
{
    private Foo $foo;
    private string $password;

    public function __construct(Foo $foo, string $password)
    {
        $this->foo = $foo;
        $this->password = $password;
    }

    public function getFoo(): Foo
    {
        return $this->foo;
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    public function isAsync() : bool
    {
        return true;
    }
}
```

#### Raise event in your business layer

[](#raise-event-in-your-business-layer)

```
use \Cvek\DomainEventsBundle\Entity\RaiseEventsInterface;
use \Cvek\DomainEventsBundle\Entity\RaiseEventsTrait;

class Foo implements RaiseEventsInterface
{
    use RaiseEventsTrait;

    private string $name;

    public function setName(string $name): self
    {
        $this->raise(new FooNameChanged($this, $this->name, $name));
        $this->name = $name;

        return $this;
    }

    public function setPassword(string $password): self
    {
        $this->raise(new FooPasswordChanged($this, $password));

        return $this;
    }
}
```

#### Catch event in listener

[](#catch-event-in-listener)

When `flush` operation will be invoked, all the events, raised in your entities, will be collected and dispatched. You can listen on them in a usual manner.

##### Listen on sync message

[](#listen-on-sync-message)

```
use \Symfony\Component\EventDispatcher\EventSubscriberInterface;
use \Doctrine\ORM\Events;

final class FooNameListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            FooNameChanged::class => 'onNameChange'
        ];
    }

    public function onNameChange(FooNameChanged $event): void
    {
        if ($event->getLifecycleEvent() === Events::preFlush) {
            // your custom logic on preFlush moment: logging, validation etc...
        }

        if ($event->getLifecycleEvent() === Events::onFlush) {
            // your custom logic on onFlush moment
        }

        if ($event->getLifecycleEvent() === Events::postFlush) {
            // your custom logic on postFlush moment
        }
    }
}
```

##### Listen on async message

[](#listen-on-async-message)

```
use \Doctrine\ORM\Events;
use \Symfony\Component\Messenger\Handler\MessageHandlerInterface;

final class FooPasswordHandler implements MessageHandlerInterface
{
    public function __invoke(FooPasswordChanged $event)
    {
        if ($event->getLifecycleEvent() === Events::preFlush) {
            // your custom logic on preFlush moment: logging, validation etc...
        }

        if ($event->getLifecycleEvent() === Events::onFlush) {
            // your custom logic on onFlush moment
        }

        if ($event->getLifecycleEvent() === Events::postFlush) {
            // your custom logic on postFlush moment
        }
    }
}
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 97.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~60 days

Recently: every ~367 days

Total

30

Last Release

531d ago

Major Versions

1.4.2 → 2.0.02020-04-09

2.5.2 → 3.0.02022-05-12

3.0.0 → 4.0.02024-12-03

PHP version history (3 changes)1.0.0PHP ^7.4

1.4.1PHP ^7.1

2.5.2PHP ^7.4|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/908a2e66bcbeed152674592f289573ad469d0d7c8a84c0f298bdb94bba426621?d=identicon)[CvekCoding](/maintainers/CvekCoding)

---

Top Contributors

[![CvekCoding](https://avatars.githubusercontent.com/u/36374606?v=4)](https://github.com/CvekCoding "CvekCoding (41 commits)")[![sanya-misharin](https://avatars.githubusercontent.com/u/25198080?v=4)](https://github.com/sanya-misharin "sanya-misharin (1 commits)")

---

Tags

eventsymfonyddddomaindomain-events

### Embed Badge

![Health badge](/badges/cvek-domain-events/health.svg)

```
[![Health](https://phpackages.com/badges/cvek-domain-events/health.svg)](https://phpackages.com/packages/cvek-domain-events)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[a2lix/translation-form-bundle

Translate your doctrine objects easily with some helpers

3376.9M38](/packages/a2lix-translation-form-bundle)[pugx/autocompleter-bundle

Add an autocomplete type to forms

93861.6k3](/packages/pugx-autocompleter-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
