PHPackages                             neuron-php/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. neuron-php/events

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

neuron-php/events
=================

Event mechanism.

0.6.14(4mo ago)02.6k↑66.7%1MITPHPCI passing

Since Aug 25Pushed 4mo agoCompare

[ Source](https://github.com/Neuron-PHP/events)[ Packagist](https://packagist.org/packages/neuron-php/events)[ RSS](/packages/neuron-php-events/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelogDependencies (3)Versions (25)Used By (1)

[![CI](https://github.com/Neuron-PHP/events/actions/workflows/ci.yml/badge.svg)](https://github.com/Neuron-PHP/events/actions)[![codecov](https://camo.githubusercontent.com/06d672fd2f3db06f922e12d792119409a327dc8d11b3ee2aa62beba2066007bc/68747470733a2f2f636f6465636f762e696f2f67682f4e6575726f6e2d5048502f6576656e74732f6272616e63682f646576656c6f702f67726170682f62616467652e737667)](https://codecov.io/gh/Neuron-PHP/events)

Neuron-PHP Events
=================

[](#neuron-php-events)

A flexible event-driven programming component for PHP 8.4+ that provides a robust framework for managing events, listeners, and broadcasters with support for multiple broadcasting strategies.

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

[](#table-of-contents)

- [Installation](#installation)
- [Core Concepts](#core-concepts)
- [Quick Start](#quick-start)
- [Components](#components)
    - [Events](#events)
    - [Emitter](#emitter)
    - [Broadcasters](#broadcasters)
    - [Listeners](#listeners)
- [Usage Examples](#usage-examples)
- [Advanced Features](#advanced-features)
- [Broadcasting Strategies](#broadcasting-strategies)
- [Integration](#integration)
- [Testing](#testing)
- [Best Practices](#best-practices)
- [More Information](#more-information)

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.4 or higher
- Composer
- Extensions: curl, json

### Install via Composer

[](#install-via-composer)

```
composer require neuron-php/events
```

Core Concepts
-------------

[](#core-concepts)

The Events component implements a publish-subscribe pattern with the following key concepts:

- **Events**: Objects representing significant state changes in your application
- **Emitter**: Central hub for dispatching events to broadcasters
- **Broadcasters**: Components that distribute events to listeners
- **Listeners**: Objects that respond to specific events

### Event Flow

[](#event-flow)

```
Application → Event → Emitter → Broadcasters → Listeners

```

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

[](#quick-start)

### 1. Create an Event

[](#1-create-an-event)

```
use Neuron\Events\IEvent;

class UserRegisteredEvent implements IEvent
{
    public function __construct(
        public readonly int $userId,
        public readonly string $email,
        public readonly DateTime $registeredAt
    ) {}
}
```

### 2. Create Listeners

[](#2-create-listeners)

```
use Neuron\Events\IListener;

class SendWelcomeEmailListener implements IListener
{
    public function event($event): void
    {
        // Send welcome email to user
        $mailer = new Mailer();
        $mailer->send($event->email, 'Welcome!', 'Thanks for registering!');
    }
}

class UpdateAnalyticsListener implements IListener
{
    public function event($event): void
    {
        // Update registration analytics
        Analytics::track('user.registered', [
            'user_id' => $event->userId,
            'timestamp' => $event->registeredAt
        ]);
    }
}
```

### 3. Configure and Use

[](#3-configure-and-use)

```
use Neuron\Events\Emitter;
use Neuron\Events\Broadcasters\Generic;

// Set up the event system
$emitter = new Emitter();
$broadcaster = new Generic();
$emitter->registerBroadcaster($broadcaster);

// Register listeners
$emitter->addListener(
    UserRegisteredEvent::class,
    new SendWelcomeEmailListener()
);
$emitter->addListener(
    UserRegisteredEvent::class,
    new UpdateAnalyticsListener()
);

// Emit the event
$event = new UserRegisteredEvent(123, 'user@example.com', new DateTime());
$emitter->emit($event);
```

Components
----------

[](#components)

### Events

[](#events)

Events are simple objects that implement the `IEvent` interface and carry data about state changes.

#### Event Interface

[](#event-interface)

```
namespace Neuron\Events;

interface IEvent
{
    // Marker interface - no required methods
}
```

#### Event Examples

[](#event-examples)

```
// Domain event
class OrderCompletedEvent implements IEvent
{
    public function __construct(
        public readonly int $orderId,
        public readonly float $total,
        public readonly array $items
    ) {}
}

// System event
class CacheInvalidatedEvent implements IEvent
{
    public function __construct(
        public readonly string $key,
        public readonly ?string $tag = null
    ) {}
}

// Integration event
class WebhookReceivedEvent implements IEvent
{
    public function __construct(
        public readonly string $source,
        public readonly array $payload,
        public readonly array $headers
    ) {}
}
```

### Emitter

[](#emitter)

The `Emitter` class is the central coordinator for the event system, managing broadcasters and event distribution.

#### Key Methods

[](#key-methods)

```
class Emitter
{
    // Register a broadcaster
    public function registerBroadcaster(IBroadcaster $broadcaster): void;

    // Get all registered broadcasters
    public function getBroadcasters(): array;

    // Add listener to all broadcasters
    public function addListener(string $eventName, IListener $listener): bool;

    // Emit an event to all broadcasters
    public function emit(IEvent $event): void;
}
```

#### Usage

[](#usage)

```
$emitter = new Emitter();

// Register multiple broadcasters
$emitter->registerBroadcaster(new Generic());
$emitter->registerBroadcaster(new Log($logger));
$emitter->registerBroadcaster(new AsyncBroadcaster());

// Add listeners (applied to all broadcasters)
$emitter->addListener(OrderCompletedEvent::class, new InventoryListener());
$emitter->addListener(OrderCompletedEvent::class, new InvoiceListener());

// Emit events
$emitter->emit(new OrderCompletedEvent($orderId, $total, $items));
```

### Broadcasters

[](#broadcasters)

Broadcasters are responsible for distributing events to registered listeners. The component includes several built-in broadcasters.

#### Broadcaster Interface

[](#broadcaster-interface)

```
namespace Neuron\Events\Broadcasters;

interface IBroadcaster
{
    public function addListener(string $eventName, IListener $listener): bool;
    public function broadcast($event): void;
}
```

#### Generic Broadcaster

[](#generic-broadcaster)

The default in-memory broadcaster for synchronous event processing.

```
use Neuron\Events\Broadcasters\Generic;

$broadcaster = new Generic();
$broadcaster->addListener(UserLoginEvent::class, new AuditListener());
$broadcaster->broadcast(new UserLoginEvent($userId));
```

#### Log Broadcaster

[](#log-broadcaster)

Writes all event activity to a log destination for debugging and auditing.

```
use Neuron\Events\Broadcasters\Log;
use Neuron\Log\Logger;

$logger = new Logger('events.log');
$logBroadcaster = new Log($logger);

// All events will be logged
$emitter->registerBroadcaster($logBroadcaster);
```

### Listeners

[](#listeners)

Listeners respond to events by implementing the `IListener` interface.

#### Listener Interface

[](#listener-interface)

```
namespace Neuron\Events;

interface IListener
{
    public function event( IEvent $event): void;
}
```

#### Listener Examples

[](#listener-examples)

```
// Database listener
class PersistEventListener implements IListener
{
    private PDO $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    public function event(IEvent $event): void
    {
        $stmt = $this->db->prepare(
            'INSERT INTO events (type, data, created_at) VALUES (?, ?, ?)'
        );
        $stmt->execute([
            get_class($event),
            json_encode($event),
            date('Y-m-d H:i:s')
        ]);
    }
}

// Notification listener
class SlackNotificationListener implements IListener
{
    private SlackClient $slack;

    public function __construct(SlackClient $slack)
    {
        $this->slack = $slack;
    }

    public function event($event): void
    {
        if ($event instanceof CriticalErrorEvent) {
            $this->slack->sendMessage('#alerts', [
                'text' => 'Critical error occurred!',
                'attachments' => [
                    [
                        'color' => 'danger',
                        'title' => $event->message,
                        'text' => $event->stackTrace
                    ]
                ]
            ]);
        }
    }
}
```

Integration
-----------

[](#integration)

Testing
-------

[](#testing)

### Unit Testing Events

[](#unit-testing-events)

```
use PHPUnit\Framework\TestCase;

class EventSystemTest extends TestCase
{
    public function testEventEmission(): void
    {
        $emitter = new Emitter();
        $broadcaster = new Generic();
        $emitter->registerBroadcaster($broadcaster);

        $listener = $this->createMock(IListener::class);
        $listener->expects($this->once())
                 ->method('event')
                 ->with($this->isInstanceOf(UserLoginEvent::class));

        $emitter->addListener(UserLoginEvent::class, $listener);
        $emitter->emit(new UserLoginEvent(123));
    }

    public function testMultipleListeners(): void
    {
        $emitter = new Emitter();
        $emitter->registerBroadcaster(new Generic());

        $called = [];

        $listener1 = new class($called) implements IListener {
            public function __construct(private array &$called) {}
            public function event($event): void {
                $this->called[] = 'listener1';
            }
        };

        $listener2 = new class($called) implements IListener {
            public function __construct(private array &$called) {}
            public function event($event): void {
                $this->called[] = 'listener2';
            }
        };

        $emitter->addListener(TestEvent::class, $listener1);
        $emitter->addListener(TestEvent::class, $listener2);
        $emitter->emit(new TestEvent());

        $this->assertEquals(['listener1', 'listener2'], $called);
    }
}
```

More Information
----------------

[](#more-information)

- **Neuron Framework**: [neuronphp.com](http://neuronphp.com)
- **GitHub**: [github.com/neuron-php/events](https://github.com/neuron-php/events)
- **Core Component**: [github.com/neuron-php/core](https://github.com/neuron-php/core) - Contains Event singleton for application-wide events
- **Packagist**: [packagist.org/packages/neuron-php/events](https://packagist.org/packages/neuron-php/events)

License
-------

[](#license)

MIT License - see LICENSE file for details

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance77

Regular maintenance activity

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.9% 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 ~89 days

Recently: every ~15 days

Total

23

Last Release

125d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1099983?v=4)[Lee Jones](/maintainers/ljonesfl)[@ljonesfl](https://github.com/ljonesfl)

---

Top Contributors

[![ljonesfl](https://avatars.githubusercontent.com/u/1099983?v=4)](https://github.com/ljonesfl "ljonesfl (125 commits)")[![hakobyansen](https://avatars.githubusercontent.com/u/43189667?v=4)](https://github.com/hakobyansen "hakobyansen (4 commits)")

---

Tags

eventeventbuseventsphp8

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/neuron-php-events/health.svg)

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

PHPackages © 2026

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