PHPackages                             monkeyscloud/monkeyslegion-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. [Framework](/categories/framework)
4. /
5. monkeyscloud/monkeyslegion-events

ActiveLibrary[Framework](/categories/framework)

monkeyscloud/monkeyslegion-events
=================================

High-performance PSR-14 event dispatcher with typed interceptors, attribute-based listeners, event sourcing, and dispatch metrics for the MonkeysLegion framework.

2.0.0(2mo ago)11.9k↓31.5%5MITPHPPHP ^8.4

Since Jul 24Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Events)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-events)[ RSS](/packages/monkeyscloud-monkeyslegion-events/feed)WikiDiscussions main Synced 2d ago

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

MonkeysLegion Events v2
=======================

[](#monkeyslegion-events-v2)

[![PHP](https://camo.githubusercontent.com/7ee6e059598f89d0c686b058a5524ccebefb7d5feb16eb0902fa4a11b1c564d1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e342d3838393242462e737667)](https://php.net)[![PSR-14](https://camo.githubusercontent.com/c558dc6bcb205c2505a51d420e3eb4f2e27c3a4387f328c7493fe86ddbd38b34/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d2d31342d636f6d706c69616e742d677265656e2e737667)](https://www.php-fig.org/psr/psr-14/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

> High-performance PSR-14 event dispatcher with typed interceptors, attribute-based listeners, event sourcing, circuit breakers, and dispatch metrics for the MonkeysLegion framework.

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

[](#installation)

```
composer require monkeyscloud/monkeyslegion-events:^2.0
```

Features
--------

[](#features)

FeatureDescription**PSR-14 Compliant**Full `EventDispatcherInterface` + `StoppableEventInterface`**5 PHP Attributes**`#[Listener]`, `#[Subscriber]`, `#[ListenWhen]`, `#[BeforeEvent]`, `#[AfterEvent]`**Priority + FIFO**Higher priority runs first; equal priority preserves registration order**One-Shot Listeners**`once()` — auto-removed after first invocation**Wildcard Listeners**Pattern matching: `User*` catches `UserCreated`, `UserDeleted`, etc.**Event Subscribers**Multi-event handler classes (Laravel + Symfony parity)**Stoppable Events**`$event->stopPropagation()` halts the listener chain**Interceptor Pipeline****NOVEL** — Before/After hooks (AOP-style)**Conditional Listeners****NOVEL** — `#[ListenWhen]` with guard method**Circuit Breaker****NOVEL** — Auto-disable failing listeners after N failures**Event Store/Replay****NOVEL** — Record &amp; replay events for testing/debugging**Dispatch Metrics****NOVEL** — Per-event timing and count tracking**Correlation IDs****NOVEL** — Hex-based event tracing across request scope**Safe Mode**Catch listener exceptions instead of crashing**Batch Dispatch**Dispatch multiple events in sequence**ShouldQueue Marker**Flag listeners for async/queue processing**ShouldBroadcast**Flag events for WebSocket/SSE broadcasting**PHP 8.4 Native**Property hooks, backed enums, asymmetric visibilityQuick Start
-----------

[](#quick-start)

```
use MonkeysLegion\Events\Event;
use MonkeysLegion\Events\EventDispatcher;
use MonkeysLegion\Events\ListenerProvider;

// Define an event
final class UserCreated extends Event
{
    public function __construct(
        public readonly string $email,
    ) {
        parent::__construct();
    }
}

// Register listeners
$provider = new ListenerProvider();
$provider->add(UserCreated::class, function (UserCreated $event) {
    echo "Welcome, {$event->email}!";
});

// Dispatch
$dispatcher = new EventDispatcher($provider);
$dispatcher->dispatch(new UserCreated('jorge@monkeyscloud.com'));
```

Attribute-Based Listeners
-------------------------

[](#attribute-based-listeners)

```
use MonkeysLegion\Events\Attribute\Listener;

#[Listener(event: UserCreated::class, priority: 10)]
final class SendWelcomeEmail
{
    public function __invoke(UserCreated $event): void
    {
        // Send email to $event->email
    }
}

// Register via attribute scanning
$provider->addFromAttributes(new SendWelcomeEmail());
```

Conditional Listeners (Novel)
-----------------------------

[](#conditional-listeners-novel)

```
use MonkeysLegion\Events\Attribute\Listener;
use MonkeysLegion\Events\Attribute\ListenWhen;

#[Listener(event: OrderPlaced::class)]
#[ListenWhen(method: 'isHighValue')]
final class OnHighValueOrder
{
    public function isHighValue(OrderPlaced $event): bool
    {
        return $event->amount > 1000;
    }

    public function __invoke(OrderPlaced $event): void
    {
        // Only called when amount > 1000
    }
}
```

Interceptor Pipeline (Novel)
----------------------------

[](#interceptor-pipeline-novel)

AOP-style before/after hooks that wrap the regular listener chain:

```
use MonkeysLegion\Events\Attribute\BeforeEvent;
use MonkeysLegion\Events\Attribute\AfterEvent;

final class OrderInterceptor
{
    #[BeforeEvent(event: OrderPlaced::class)]
    public function validate(OrderPlaced $event): void
    {
        // Runs BEFORE regular listeners
    }

    #[AfterEvent(event: OrderPlaced::class)]
    public function audit(OrderPlaced $event): void
    {
        // Runs AFTER all regular listeners
    }
}

$provider->addFromAttributes(new OrderInterceptor());
```

### Global Interceptors

[](#global-interceptors)

```
use MonkeysLegion\Events\Interceptor\TimingInterceptor;
use MonkeysLegion\Events\Interceptor\LoggingInterceptor;
use MonkeysLegion\Events\EventMetrics;

$metrics = new EventMetrics();
$dispatcher->addInterceptor(new TimingInterceptor($metrics));
$dispatcher->addInterceptor(new LoggingInterceptor($psrLogger));

$dispatcher->dispatch(new OrderPlaced(42, 99.99));

echo $metrics->countFor(OrderPlaced::class);   // 1
echo $metrics->averageFor(OrderPlaced::class);  // 0.123 ms
```

Event Subscribers
-----------------

[](#event-subscribers)

```
use MonkeysLegion\Events\EventSubscriberInterface;

final class UserEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserCreated::class => 'onUserCreated',
            UserDeleted::class => ['onUserDeleted', 10], // with priority
            OrderPlaced::class => [
                ['onOrderLog', 10],
                ['onOrderNotify', 5],
            ],
        ];
    }

    public function onUserCreated(UserCreated $event): void { /* ... */ }
    public function onUserDeleted(UserDeleted $event): void { /* ... */ }
    public function onOrderLog(OrderPlaced $event): void { /* ... */ }
    public function onOrderNotify(OrderPlaced $event): void { /* ... */ }
}

$provider->addSubscriber(new UserEventSubscriber());
```

Wildcard Listeners
------------------

[](#wildcard-listeners)

```
// Matches UserCreated, UserDeleted, UserUpdated, etc.
$provider->addWildcard('*UserCreated', function (object $event) {
    // Handle any event matching the pattern
});
```

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

[](#stoppable-events)

```
$provider->add(GenericEvent::class, function (Event $event) {
    $event->stopPropagation(); // Subsequent listeners won't run
}, priority: 10);

$provider->add(GenericEvent::class, function () {
    // This will NOT be called
}, priority: 0);
```

Event Store &amp; Replay (Novel)
--------------------------------

[](#event-store--replay-novel)

```
use MonkeysLegion\Events\Store\EventStore;

$store = new EventStore();
$dispatcher = new EventDispatcher($provider, store: $store);

$dispatcher->dispatch(new UserCreated('a@test.com'));
$dispatcher->dispatch(new OrderPlaced(1, 50.0));

// Query recorded events
$users = $store->ofType(UserCreated::class); // [UserCreated]
echo $store->size; // 2

// Replay all events through another dispatcher
$store->replay($anotherDispatcher);
```

Dispatch Result &amp; Metrics
-----------------------------

[](#dispatch-result--metrics)

```
$result = $dispatcher->dispatchWithResult(new UserCreated('test@test.com'));

echo $result->listenersInvoked; // 3
echo $result->durationMs;       // 0.456
echo $result->stopped;           // false
echo $result->isClean();         // true (no errors)

// Batch dispatch
$results = $dispatcher->dispatchBatch([
    new UserCreated('a@test.com'),
    new OrderPlaced(1, 50.0),
]);
```

Circuit Breaker (Novel)
-----------------------

[](#circuit-breaker-novel)

Listeners that fail repeatedly are auto-disabled:

```
$descriptor = new ListenerDescriptor(
    listener:         fn() => throw new \RuntimeException('fail'),
    eventClass:       OrderPlaced::class,
    circuitThreshold: 3,    // Trip after 3 failures
    circuitResetTime: 60,   // Try again after 60 seconds
);
```

Safe Mode
---------

[](#safe-mode)

```
// Catch listener exceptions instead of crashing
$dispatcher = new EventDispatcher($provider, safeMode: true);

$result = $dispatcher->dispatchWithResult(new OrderPlaced(1, 50.0));
// Errors captured in $result->errors instead of throwing
```

Async/Queue Markers
-------------------

[](#asyncqueue-markers)

```
use MonkeysLegion\Events\Contract\ShouldQueue;

#[Listener(event: OrderPlaced::class)]
final class ProcessPayment implements ShouldQueue
{
    public function __invoke(OrderPlaced $event): void
    {
        // Will be dispatched to queue by integration layer
    }
}
```

Correlation Tracking
--------------------

[](#correlation-tracking)

```
$event = new UserCreated('test@test.com');
echo $event->correlationId;  // "a1b2c3d4..." (auto-generated 32-char hex correlation ID)
echo $event->name;            // "UserCreated" (auto-derived)
echo $event->timestamp;       // DateTimeImmutable
```

PHP 8.4 Features Used
---------------------

[](#php-84-features-used)

FeatureWhere**Property Hooks**`Event::$isPropagationStopped`, `Event::$name`, `EventMetrics`, `ListenerProvider::$count`, `EventStore::$size`, `EventDispatcher::$totalDispatches`**Asymmetric Visibility**`Event::$timestamp`, `Event::$correlationId`, `ListenerDescriptor`**Backed Enum**`EventType` (Before/On/After)**`readonly` classes**`DispatchResult`, all Attributes**`match` expressions**`EventType::label()`**`new` in initializers**`Event::$timestamp`, `ListenerDescriptor::$registeredAt`**PHP 8 Attributes**5 attributes across `Attribute/` namespaceChangelog
---------

[](#changelog)

### 2.0.0 — Complete Rebuild

[](#200--complete-rebuild)

**BREAKING CHANGE**: Full API redesign from v1.

- **Architecture**: Replaced minimal PSR-14 shim with full interceptor-pipeline dispatcher
- **5 Attributes**: `#[Listener]`, `#[Subscriber]`, `#[ListenWhen]`, `#[BeforeEvent]`, `#[AfterEvent]`
- **Contracts**: `ShouldQueue`, `ShouldBroadcast`, `EventSubscriberInterface`
- **Interceptors**: `InterceptorInterface`, `LoggingInterceptor`, `TimingInterceptor`
- **Event Store**: In-memory record &amp; replay for testing/debugging/event sourcing
- **Novel Features**: Conditional listeners, circuit breaker, wildcard matching, correlation tracking, dispatch metrics, batch dispatch, safe mode
- **PHP 8.4**: Property hooks, backed enums, asymmetric visibility, `new` in initializers
- **Tests**: 59 tests, 119 assertions

Requirements
------------

[](#requirements)

- PHP 8.4+
- `psr/event-dispatcher` ^1.0

### Optional

[](#optional)

- `psr/log` ^3.0 — For `LoggingInterceptor`

License
-------

[](#license)

MIT

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance84

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 77.8% 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 ~87 days

Total

4

Last Release

83d ago

Major Versions

1.0.1 → 2.0.0.x-dev2026-04-11

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2913369?v=4)[Jorge Peraza](/maintainers/yorchperaza)[@yorchperaza](https://github.com/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (7 commits)")[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (1 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-events/health.svg)

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

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6942.5M421](/packages/drupal-core-recommended)[spiral/framework

Spiral, High-Performance PHP/Go Framework

2.1k2.2M66](/packages/spiral-framework)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)

PHPackages © 2026

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