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

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

koriit/eventdispatcher
======================

Simple event dispatcher based on PHP-DI

v2.0.0(8y ago)366411MITPHP

Since Jun 16Pushed 8y ago1 watchersCompare

[ Source](https://github.com/Koriit/EventDispatcher)[ Packagist](https://packagist.org/packages/koriit/eventdispatcher)[ Docs](https://github.com/Koriit/EventDispatcher)[ RSS](/packages/koriit-eventdispatcher/feed)WikiDiscussions master Synced 3w ago

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

EventDispatcher
---------------

[](#eventdispatcher)

[![Build Status](https://camo.githubusercontent.com/273d8f4ac2b010c03a6dbca2ab9528d10823f6605a9abe2c6fe5fee1932ef614/68747470733a2f2f7472617669732d63692e6f72672f4b6f726969742f4576656e74446973706174636865722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Koriit/EventDispatcher)[![Coverage Status](https://camo.githubusercontent.com/b9fadcdb5e3da6235c09aa0d761fe830245fc75e142891e043a9d73fa26ea52a/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4b6f726969742f4576656e74446973706174636865722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/Koriit/EventDispatcher?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/5ac6eefc2c20d89af70c883d1506ac30808dd58356b8d3b1230b00b170138226/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f4b6f726969742f4576656e74446973706174636865722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/Koriit/EventDispatcher/?branch=master)[![StyleCI](https://camo.githubusercontent.com/764dbfae95cc750db955d5aa2bc74210aecd50f100003aec77f6483fed6302fd/68747470733a2f2f7374796c6563692e696f2f7265706f732f37373434373934332f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/77447943)[![SensioLabsInsight](https://camo.githubusercontent.com/5609509dab351cb8bcf939dc277b99b1b3dbd8b85fd5096b2b8e77b59680b216/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f65323262353461392d623263652d346234322d386236622d3566353632323138646133342f6d696e692e706e67)](https://insight.sensiolabs.com/projects/e22b54a9-b2ce-4b42-8b6b-5f562218da34)

[![Latest Stable Version](https://camo.githubusercontent.com/cb5361c01e80affb8eba554acdd63a522abfc47624a4c6fea5108969c0640d84/68747470733a2f2f706f7365722e707567782e6f72672f6b6f726969742f6576656e74646973706174636865722f762f737461626c65)](https://packagist.org/packages/koriit/eventdispatcher)[![License](https://camo.githubusercontent.com/d5876892b487acd3d1062cac9066466280d704321fb4c81fd89f94d8ca691ad1/68747470733a2f2f706f7365722e707567782e6f72672f6b6f726969742f6576656e74646973706174636865722f6c6963656e7365)](https://packagist.org/packages/koriit/eventdispatcher)

Simple event dispatcher based on [PHP-DI](http://php-di.org).

This library **does not** aim to be general purpose library or to cover all possible use cases. What this library **does** aim to be is perfect choice for those who use PHP-DI and prefer to use [PHP Definitions](http://php-di.org/doc/php-definitions.html).

The goal is to create as decoupled code as possible. The code that uses the dispatcher may not know its listeners, and the other way around, the listeners may not even know that they are actually used as listeners!

Install
-------

[](#install)

EventDispatcher is available via composer:

```
composer require koriit/eventdispatcher
```

Versions
--------

[](#versions)

This library depends on PHP-DI and is thus affected by compatibility breaks coming from it.

### v2

[](#v2)

Tested with PHP-DI ^6.0.

### v1

[](#v1)

Tested with PHP-DI ^5.4.

Usage
-----

[](#usage)

You are encouraged to familiarize yourself with `Koriit\EventDispatcher\EventDispatcherInterface` and `Koriit\EventDispatcher\EventContextInterface` as those two interfaces are everything you need to work with this library.

Basic example:

```
// configure and build your container

$dispatcher = new EventDispatcher($container);

$listener = function (LoggerInterface $logger, Request $request) {
    $logger->info($request->getMethod().' '.$request->getPathInfo());
};

$dispatcher->addListener("init", $listener, 10);

$dispatcher->dispatch("init");
```

Naturally since we are using PHP-DI then we would create a definition for `Koriit\EventDispatcher\EventDispatcherInterface`.

A listener may be anything that [can be invoked by PHP-DI](http://php-di.org/doc/container.html#call):

```
// MyClass.php
class MyClass
{
    public function logRequest(LoggerInterface $logger, Request $request)
    {
        $logger->info($request->getMethod().' '.$request->getPathInfo());
    }
}
```

```
// configure and build your container

$dispatcher = $container->get(EventDispatcherInterface::class);

$dispatcher->addListener(ApplicationLifecycle::INITIALIZING, [MyClass::class, 'logRequest'], 10);

$dispatcher->dispatch(ApplicationLifecycle::INITIALIZING);
```

Even interfaces:

```
// MyInterface.php
interface MyInterface
{
    public function logRequest(LoggerInterface $logger, Request $request);
}
```

```
// MyClass.php
class MyClass implements MyInterface
{
    public function logRequest(LoggerInterface $logger, Request $request)
    {
        $logger->info($request->getMethod().' '.$request->getPathInfo());
    }
}
```

```
// configure and build your container

$dispatcher = $container->get(EventDispatcherInterface::class);

$dispatcher->addListener(InitializationEvent::class, [MyInterface::class, 'logRequest'], 10);

$dispatcher->dispatch(InitializationEvent::class, ["event" => new InitializationEvent()]);
```

For above example to work you need to configure a definition for *MyInterface*, of course.

**Warning:**
Event dispatcher doesn't work well with listeners which implement fluent interface or allow for method chaining. For more information, read about stopping dispatchemnt chain below.

Adding listeners
----------------

[](#adding-listeners)

There are 2 ways to subscribe a listener. In both cases you have to specify name of the event and calling priority. The higher the priority value the later the listener will be called. Listeners with the same priority will be called in the order they have been subscribed. You can entirely omit priority parameter as it defaults to 0.

### addListener

[](#addlistener)

First, by using `addListener` method on `Koriit\EventDispatcher\EventDispatcher` object.

```
interface EventDispatcherInterface
{
  // ..

  /**
   * Subscribes a listener to given event with specific priority.
   *
   * Listener must be invokable by PHP-DI.
   *
   * The higher the priority value the later the listener will be called.
   * Listeners with the same priority will be called in the order they have been subscribed.
   *
   * @param mixed  $eventName
   * @param mixed  $listener
   * @param int    $priority
   */
  public function addListener($eventName, $listener, $priority = 0);

  // ...
}
```

### addListeners

[](#addlisteners)

Second, by using `addListeners` method on `Koriit\EventDispatcher\EventDispatcher` object.

```
interface EventDispatcherInterface
{
  // ..

  /**
   * Subscribes listeners in bulk.
   *
   * Listeners array is a simple structure of 3 levels:
   * - At first level it is associative array where keys are names of registered events
   * - At second level it is indexed array where keys are priority values
   * - At third level it is simple list containing listeners subscribed to given event with given priority
   *
   * @param array $listeners
   *
   * @return void
   */
  public function addListeners($listeners);

  // ...
}
```

Listeners array is a simple structure of 3 levels:

- At first level it is associative array where keys are names of registered events
- At second level it is indexed array where keys are priority values
- At third level it is simple list containing listeners subscribed to given event with given priority

Example:

```
// listners.php
// namespace and imports...

return [
    CLIApplicationLifecycle::INITIALIZING => [
        0 => [
            [ConfigServiceInterface::class, 'init'],
        ],
        1 => [
            [CommandsServiceInterface::class, 'load'],
        ],
    ],

    CLIApplicationLifecycle::FINALIZING => [
        100 => [
            function (LoggerInterface $logger, InputInterface $input, $exitCode) {
                $logger->info('Returning from command `'.$input.'` with exit code '.$exitCode);
            },
        ],
    ],
];
```

```
// ...

$dispatcher->addListeners(include 'listeners.php');

// ...
```

Dispatchment
------------

[](#dispatchment)

Dispatchment is a simple process of invoking all listeners subscribed to dispatched event.

```
interface EventDispatcherInterface
{
    // ...

    /**
     * Dispatches an event with given name.
     *
     * @param mixed $eventName
     * @param array $parameters
     *
     * @return EventContextInterface
     */
    public function dispatch($eventName, $parameters = []);

    // ...
}
```

```
// ..

$dispatcher->dispatch(ApplicationLifecycle::INITIALIZING);
```

### Stopping dispatchment

[](#stopping-dispatchment)

If any listener in the dispatchment chain returns a value that can be evaluated as *true*, the dispachment is stopped and all the remaining listeners are skipped. You can also achieve this by calling `stop` on event context.

While this design simplifies the process and **does not require wiring listeners with event dispatcher**, it makes it problematic to work with listeners that return values which cannot be interpreted as success or failure. This especially holds true for methods which allow for method chaining or implement fluent interface. To work around this problem you can use `stop` and `ignoreReturnValue` methods on event context, though, that requires wiring your listener with event context. Everything is a trade-off, someone once said.

### Context

[](#context)

Event context is simple data object holding information about the dispatchment process. See `Koriit\EventDispatcher\EventContextInterface` for more information.

### Parameters

[](#parameters)

You can pass additional parameters to be used by invoker while injecting listener arguments by name.

```
// ..

$dispatcher->dispatch(InitializationEvent::class, ["event" => new InitializationEvent()]);
```

```
function listener($event) {
  // $event is InitializationEvent object
}
```

### eventName, eventContext, eventDispatcher

[](#eventname-eventcontext-eventdispatcher)

There are 3 parameters injected by event dispatcher itself:

1. eventName - name of the event dispatched
2. eventContext - reference to the context object of current dispatchment
3. eventDispatcher - reference to the event dispatcher itself; this allows for nested dispatchments

You cannot override them as using those keys in parameters array causes exception.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity67

Established project with proven stability

 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

Every ~80 days

Total

5

Last Release

2981d ago

Major Versions

v1.0.1 → v2.0.02018-05-02

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8916393?v=4)[Aleksander Stelmaczonek](/maintainers/Koriit)[@Koriit](https://github.com/Koriit)

---

Top Contributors

[![Koriit](https://avatars.githubusercontent.com/u/8916393?v=4)](https://github.com/Koriit "Koriit (58 commits)")

---

Tags

event-dispatcherphpphp-dieventdispatchereventdispatcherphp-dikoriit

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[contributte/event-dispatcher

Best event dispatcher / event manager / event emitter for Nette Framework

292.5M19](/packages/contributte-event-dispatcher)

PHPackages © 2026

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