PHPackages                             jardisadapter/eventdispatcher - 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. jardisadapter/eventdispatcher

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jardisadapter/eventdispatcher
=============================

PSR-14 event dispatcher with listener registry, priority ordering, and stoppable event support

v1.0.0(1mo ago)056↓87.3%1MITPHPPHP &gt;=8.2CI passing

Since Jun 1Pushed 2w agoCompare

[ Source](https://github.com/jardisAdapter/eventdispatcher)[ Packagist](https://packagist.org/packages/jardisadapter/eventdispatcher)[ Docs](https://docs.jardis.io/en/adapter/eventdispatcher)[ RSS](/packages/jardisadapter-eventdispatcher/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (5)Versions (3)Used By (1)

Jardis Event Dispatcher
=======================

[](#jardis-event-dispatcher)

[![Build Status](https://github.com/jardisAdapter/eventdispatcher/actions/workflows/ci.yml/badge.svg)](https://github.com/jardisAdapter/eventdispatcher/actions/workflows/ci.yml/badge.svg)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE.md)[![PHP Version](https://camo.githubusercontent.com/a68b290dcc313d698dc138a1111aa83eee2f143605449d7e8b5416ea6f88558f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e322d3737374242342e737667)](https://www.php.net/)[![PHPStan Level](https://camo.githubusercontent.com/c51bda247654363d3e30bc352674dd761a9557803a14af0226eb411d6dc0006b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230382d627269676874677265656e2e737667)](phpstan.neon)[![PSR-12](https://camo.githubusercontent.com/34b10db0caa29bacd49bda5c437a8de95385f036f3230b31fa605326e18da22c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f436f64652532305374796c652d5053522d2d31322d626c75652e737667)](phpcs.xml)[![PSR-14](https://camo.githubusercontent.com/58898d95938b98bf9a9e9bc45151ec27daa3bdd97e87f07822eb53d2c108eb12/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4576656e74732d5053522d2d31342d627269676874677265656e2e737667)](https://www.php-fig.org/psr/psr-14/)

> Part of **[Jardis](https://jardis.io)** — the Domain-Driven Design platform for PHP. You model your domain; Jardis generates the production-ready hexagonal code (DTOs, Command/Query handlers, repositories, persistence). This package is part of the open-source foundation that generated code runs on.

**Domain events for PHP as first-class citizens.** A lightweight PSR-14 event dispatcher — built for DDD applications where events drive the communication between layers and contexts. No framework, no overhead, no magic. Just what you need.

---

Why this Dispatcher?
--------------------

[](#why-this-dispatcher)

- **Four classes, zero magic** — `EventDispatcher`, `ListenerProvider`, `Event`, `EventCollector`
- **Priority ordering** — listeners with higher priority are called first
- **Type-hierarchy matching** — a listener on an interface catches all implementing events
- **Stoppable events** — break the listener chain when an event is considered handled
- **EventCollector** — collect events in the domain layer, dispatch them all at once in the application layer
- **PSR-14 compliant** — works with any PSR-14 compatible code
- **100% test coverage** — no mocks, real execution only

---

Installation
------------

[](#installation)

```
composer require jardisadapter/eventdispatcher
```

---

Quick Start
-----------

[](#quick-start)

### Define an Event

[](#define-an-event)

```
use JardisAdapter\EventDispatcher\Event;

final class OrderCreated extends Event
{
    public function __construct(
        public readonly string $orderId,
    ) {
    }
}
```

### Register Listeners and Dispatch

[](#register-listeners-and-dispatch)

```
use JardisAdapter\EventDispatcher\EventDispatcher;
use JardisAdapter\EventDispatcher\ListenerProvider;

$provider = new ListenerProvider();
$provider->listen(OrderCreated::class, function (OrderCreated $event): void {
    echo "Order {$event->orderId} created!";
});

$dispatcher = new EventDispatcher($provider);
$dispatcher->dispatch(new OrderCreated('ORD-42'));
```

---

Listener Registration
---------------------

[](#listener-registration)

### Priority-based Registration

[](#priority-based-registration)

```
$provider->listen(OrderCreated::class, $sendConfirmation, priority: 10);   // first
$provider->listen(OrderCreated::class, $updateInventory, priority: 5);     // second
$provider->listen(OrderCreated::class, $logEvent);                        // last (0)
```

Higher number = higher priority = called first.

### Remove a Listener

[](#remove-a-listener)

```
$provider->remove(OrderCreated::class, $sendConfirmation);
```

### Type-Hierarchy Matching (Wildcard)

[](#type-hierarchy-matching-wildcard)

A listener on an interface or parent class catches **all events** that implement or extend it:

```
interface PaymentEventInterface {}

final class PaymentReceived extends Event implements PaymentEventInterface {}
final class PaymentFailed extends Event implements PaymentEventInterface {}

// Catches both PaymentReceived AND PaymentFailed
$provider->listen(PaymentEventInterface::class, $paymentAuditor);

// Catches EVERY event that extends Event
$provider->listen(Event::class, $globalLogger);
```

Direct and wildcard listeners are sorted together by priority.

---

Stoppable Events
----------------

[](#stoppable-events)

A listener can stop further processing:

```
$provider->listen(OrderCreated::class, function (OrderCreated $event): void {
    if ($event->orderId === 'BLOCKED') {
        $event->stopPropagation();  // no further listeners will be called
    }
}, priority: 100);

$provider->listen(OrderCreated::class, function (OrderCreated $event): void {
    // Only called if stopPropagation() was NOT invoked
});
```

Any event extending `Event` or implementing `StoppableEventInterface` supports this automatically.

---

EventCollector — Deferred Dispatch
----------------------------------

[](#eventcollector--deferred-dispatch)

Collect events in the domain layer, dispatch them later in the application layer:

```
use JardisAdapter\EventDispatcher\EventCollector;

$collector = new EventCollector();

// In the domain layer — record events
$collector->record(new OrderCreated($orderId));
$collector->record(new InventoryReserved($itemId));

// In the application layer — after the use case completes
$collector->dispatchAll($dispatcher);  // dispatches all, clears the list
```

The collector separates the **occurrence** of an event (domain) from its **distribution** (application). Ideal for use cases that produce multiple events.

```
$collector->count();     // number of collected events
$collector->events();    // read events without dispatching
$collector->clear();     // clear the list without dispatching
```

---

Error Handling
--------------

[](#error-handling)

SituationBehaviorListener throws an exceptionPropagates unchanged to the callerNo listener registeredEvent is silently ignoredEvent already stoppedNo listener is calledNo custom exception classes. Errors come from the listeners, not from the dispatcher.

---

Architecture
------------

[](#architecture)

```
EventDispatcher (implements EventDispatcherInterface)
  │
  │  dispatch(object $event): object
  │  └── iterates listeners, respects StoppableEventInterface
  │
  └── ListenerProvider (implements ListenerProviderInterface, EventListenerRegistryInterface)
        │
        ├── listen()    register listener with priority
        ├── remove()    remove a listener
        └── getListenersForEvent()
              └── type-hierarchy matching + priority sorting

Event (abstract, implements StoppableEventInterface)
  └── stopPropagation() / isPropagationStopped()

EventCollector
  └── record() → dispatchAll() / events() / clear() / count()

```

The dispatcher is the **postman** — it receives the event and delivers it to all recipients. The listener provider is the **address book**. The event collector is the **mailbox** in the domain layer.

---

DDD Layer Rules
---------------

[](#ddd-layer-rules)

LayerResponsibility**Domain**Defines event classes. Does **not** dispatch — returns events instead**Application**Receives `EventDispatcherInterface` via injection. Dispatches after use case execution**Infrastructure**Registers listeners in the `ListenerProvider`---

Jardis Foundation Integration
-----------------------------

[](#jardis-foundation-integration)

In a Jardis DDD project, the dispatcher is wired into the `DomainKernel` via `DomainApp::eventDispatcher()`:

```
// Inside a BoundedContext
$dispatcher = $this->resource()->eventDispatcher();

if ($dispatcher !== null) {
    $dispatcher->dispatch(new OrderCreated($orderId));
}
```

### Three-State Semantics

[](#three-state-semantics)

Return valueMeaning`EventDispatcher`Dispatcher active, shared via ServiceRegistry`null`Package not installed — falls back to SharedRegistry`false`Event dispatching explicitly disabled---

Development
-----------

[](#development)

```
cp .env.example .env    # Once
make install             # Install dependencies
make phpunit             # Run tests
make phpstan             # Static analysis (level 8)
make phpcs               # Coding standards (PSR-12)
```

---

Documentation
-------------

[](#documentation)

Full documentation, guides, and API reference:

**[docs.jardis.io/en/adapter/eventdispatcher](https://docs.jardis.io/en/adapter/eventdispatcher)**

---

License
-------

[](#license)

[MIT License](LICENSE.md) — free for any use, including commercial.

AI-Assisted Development
-----------------------

[](#ai-assisted-development)

This package ships with a skill for Claude Code, Cursor, Continue, and Aider. Install it in your consuming project:

```
composer require --dev jardis/dev-skills
```

More details:

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance95

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

30d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e07a1b668e9e01ee6d1b85de7b3be1c2513f68aae9494b2011d1592104d5daa0?d=identicon)[jardis](/maintainers/jardis)

---

Top Contributors

[![Headgent](https://avatars.githubusercontent.com/u/245725954?v=4)](https://github.com/Headgent "Headgent (7 commits)")

---

Tags

domain-driven-designdomain-eventsevent-dispatcherhexagonal-architecturejardisphppsr-14eventpsr-14listenerDomain Driven DesigndispatcherHeadgentjardis

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jardisadapter-eventdispatcher/health.svg)

```
[![Health](https://phpackages.com/badges/jardisadapter-eventdispatcher/health.svg)](https://phpackages.com/packages/jardisadapter-eventdispatcher)
```

PHPackages © 2026

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