PHPackages                             purpleharmonie/event-system - 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. purpleharmonie/event-system

ActiveLibrary

purpleharmonie/event-system
===========================

Purpleharmonie Event System is a flexible and powerful event dispatching library for PHP applications. It provides a robust implementation of the PSR-14 Event Dispatcher standard, along with additional features for advanced use cases.

1.0.0(1y ago)06MITPHP

Since Aug 4Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ohenekofi/Purple-Event-Dispatcher)[ Packagist](https://packagist.org/packages/purpleharmonie/event-system)[ RSS](/packages/purpleharmonie-event-system/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Purpleharmonie Event System
===========================

[](#purpleharmonie-event-system)

Table of Contents
-----------------

[](#table-of-contents)

1. [Introduction](#introduction)
2. [Features](#features)
3. [Installation](#installation)
4. [Basic Usage](#basic-usage)
5. [Advanced Concepts](#advanced-concepts)
    - [Event Subscribers](#event-subscribers)
    - [Prioritized Listeners](#prioritized-listeners)
    - [Stoppable Events](#stoppable-events)
    - [Event Validation](#event-validation)
    - [Middleware](#middleware)
    - [Conditional Event Dispatching](#conditional-event-dispatching)
    - [Asynchronous Event Handling](#asynchronous-event-handling)
6. [Integration with Dependency Injection](#integration-with-dependency-injection)
7. [Best Practices](#best-practices)
8. [API Reference](#api-reference)

Introduction
------------

[](#introduction)

Purpleharmonie Event System is a flexible and powerful event dispatching library for PHP applications. It provides a robust implementation of the PSR-14 Event Dispatcher standard, along with additional features for advanced use cases.

Features
--------

[](#features)

- PSR-14 compliant event dispatcher
- Support for event subscribers
- Prioritized event listeners
- Stoppable events
- Event validation
- Middleware support
- Conditional event dispatching
- Asynchronous event handling (hook)
- PSR-3 Logger integration
- Easy integration with dependency injection containers

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

[](#installation)

You can install the Purpleharmonie Event System using Composer:

```
composer require purpleharmonie/event-system
```

Basic Usage
-----------

[](#basic-usage)

Here's a simple example of how to use the event system:

```
use Purpleharmonie\EventSystem\EventDispatcher;
use Purpleharmonie\EventSystem\ListenerProvider;

// Create the listener provider and event dispatcher
$listenerProvider = new ListenerProvider();
$eventDispatcher = new EventDispatcher($listenerProvider);

// Define an event
class UserRegisteredEvent
{
    public function __construct(public string $username) {}
}

// Add a listener
$listenerProvider->addListener(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    echo "User registered: {$event->username}\n";
});

// Dispatch an event
$event = new UserRegisteredEvent('john_doe');
$eventDispatcher->dispatch($event);
```

Advanced Concepts
-----------------

[](#advanced-concepts)

### Event Subscribers

[](#event-subscribers)

Event subscribers allow you to group multiple event listeners in a single class:

```
use Purpleharmonie\EventSystem\Interface\EventSubscriberInterface;

class UserSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UserRegisteredEvent::class => [
                ['onUserRegistered', 10],
                ['sendWelcomeEmail', 5]
            ]
        ];
    }

    public function onUserRegistered(UserRegisteredEvent $event): void
    {
        echo "User registered: {$event->username}\n";
    }

    public function sendWelcomeEmail(UserRegisteredEvent $event): void
    {
        echo "Sending welcome email to {$event->username}\n";
    }
}

// Usage
$listenerProvider->addSubscriber(new UserSubscriber());
```

### Prioritized Listeners

[](#prioritized-listeners)

You can set priorities for listeners to control their execution order:

```
$listenerProvider->addListener(ExampleEvent::class, function(ExampleEvent $event) {
    echo "High priority listener\n";
}, 10);

$listenerProvider->addListener(ExampleEvent::class, function(ExampleEvent $event) {
    echo "Low priority listener\n";
}, -10);
```

### Stoppable Events

[](#stoppable-events)

Stoppable events allow you to prevent further event propagation:

```
use Purpleharmonie\EventSystem\StoppableEvent;

class StoppableExampleEvent extends StoppableEvent
{
    public $message;

    public function __construct(string $message)
    {
        $this->message = $message;
    }
}

$listenerProvider->addListener(StoppableExampleEvent::class, function(StoppableExampleEvent $event) {
    echo "First listener\n";
    $event->stopPropagation();
});

$listenerProvider->addListener(StoppableExampleEvent::class, function(StoppableExampleEvent $event) {
    echo "This won't be called if propagation is stopped\n";
});
```

### Event Validation

[](#event-validation)

You can implement the `ValidatableEventInterface` to add custom validation logic to your events:

```
use Purpleharmonie\EventSystem\Interface\ValidatableEventInterface;

class UserRegisteredEvent implements ValidatableEventInterface
{
    public function __construct(public string $username, public string $email) {}

    public function isValid(): bool
    {
        return !empty($this->username) && filter_var($this->email, FILTER_VALIDATE_EMAIL);
    }
}

// Add a custom validator
$eventDispatcher->addValidator(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    return strlen($event->username) >= 3;
});
```

### Middleware

[](#middleware)

Middleware allows you to intercept and modify events before they reach the listeners:

```
$eventDispatcher->addMiddleware(function($event) {
    if ($event instanceof UserRegisteredEvent) {
        $event->username = strtolower($event->username);
    }
    return $event;
});
```

### Conditional Event Dispatching

[](#conditional-event-dispatching)

The `ConditionalEventDispatcher` allows you to add conditions for event dispatching:

```
$conditionalDispatcher = new ConditionalEventDispatcher($eventDispatcher);
$conditionalDispatcher->addCondition(UserRegisteredEvent::class, function(UserRegisteredEvent $event) {
    return strlen($event->username) > 3;
});
```

### Asynchronous Event Handling

[](#asynchronous-event-handling)

You can implement the `AsyncEventDispatcherInterface` to handle events asynchronously:

```
use Purpleharmonie\EventSystem\Interface\AsyncEventDispatcherInterface;

class ExampleAsyncDispatcher implements AsyncEventDispatcherInterface
{
    public function dispatchAsync(object $event, array $context = [])
    {
        // Queue the event for asynchronous processing
        return uniqid('job_');
    }

    public function getAsyncStatus($jobIdentifier): string
    {
        // Check and return the status of the async job
    }
}

$asyncDispatcher = new ExampleAsyncDispatcher();
$eventDispatcher->setAsyncDispatcher($asyncDispatcher);

// Dispatch asynchronously
$jobId = $eventDispatcher->dispatchAsync($event, ['source' => 'web_signup']);
```

Integration with Dependency Injection
-------------------------------------

[](#integration-with-dependency-injection)

Here's an example of how to integrate the event system with a dependency injection container:

```
// services.php
$services->set('example_subscriber', ExampleSubscriber::class)
    ->asGlobal(true)
    ->asShared(true);

$services->set('logger', function ($container) {
    return new Logger('event_dispatcher');
})
->implements(LoggerInterface::class)
->asGlobal(true)
->asShared(true);

$services->set('listener_provider', function ($container) {
    $logger = $container->get('logger');
    return new ListenerProvider($logger);
})
->implements(ListenerProviderInterface::class)
->asGlobal(true)
->asShared(true);

$services->set('event_dispatcher', EventDispatcher::class)
    ->autowire()
    ->asGlobal(true)
    ->asShared(true);
```

Best Practices
--------------

[](#best-practices)

1. Keep events small and focused on a single aspect of your application.
2. Use event subscribers for organizing related listeners.
3. Utilize priorities to ensure proper execution order of listeners.
4. Implement validation for critical events to ensure data integrity.
5. Use middleware for cross-cutting concerns that apply to multiple events.
6. Consider using asynchronous event handling for time-consuming operations.

API Reference
-------------

[](#api-reference)

For a complete API reference, please generate API documentation using a tool like phpDocumentor.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 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

650d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/663ec7db842234e526db71ef5326b571972234eb7bf2ead3add61ceffc8c7360?d=identicon)[ohenekofi](/maintainers/ohenekofi)

---

Top Contributors

[![ohenekofi](https://avatars.githubusercontent.com/u/70855774?v=4)](https://github.com/ohenekofi "ohenekofi (2 commits)")

### Embed Badge

![Health badge](/badges/purpleharmonie-event-system/health.svg)

```
[![Health](https://phpackages.com/badges/purpleharmonie-event-system/health.svg)](https://phpackages.com/packages/purpleharmonie-event-system)
```

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.3k86.3M2.2k](/packages/symfony-symfony)[symfony/mailer

Helps sending emails

1.6k368.1M955](/packages/symfony-mailer)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[phpro/soap-client

A general purpose SoapClient library

8885.6M46](/packages/phpro-soap-client)[drupal/core-recommended

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

6939.5M343](/packages/drupal-core-recommended)[web-auth/webauthn-lib

FIDO2/Webauthn Support For PHP

1195.3M72](/packages/web-auth-webauthn-lib)

PHPackages © 2026

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