PHPackages                             superbalist/php-event-pubsub - 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. superbalist/php-event-pubsub

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

superbalist/php-event-pubsub
============================

An event protocol and implementation over pub/sub

4.0.3(8y ago)832.7k↓43.3%32MITPHPPHP &gt;=5.6.0

Since Jan 27Pushed 3y ago34 watchersCompare

[ Source](https://github.com/Superbalist/php-event-pubsub)[ Packagist](https://packagist.org/packages/superbalist/php-event-pubsub)[ RSS](/packages/superbalist-php-event-pubsub/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (8)Dependencies (6)Versions (12)Used By (2)

php-event-pubsub
================

[](#php-event-pubsub)

An event protocol and implementation over pub/sub

[![Author](https://camo.githubusercontent.com/abd4e3e2e71081ad01ef09a60c49d70c5e0677497f38918e740703cd02605078/687474703a2f2f696d672e736869656c64732e696f2f62616467652f617574686f722d40737570657262616c6973742d626c75652e7376673f7374796c653d666c61742d737175617265)](https://twitter.com/superbalist)[![Build Status](https://camo.githubusercontent.com/04421183d7d094baac53df68594be2f92f5360db3277b847302377e6b87d5351/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f537570657262616c6973742f7068702d6576656e742d7075627375622f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/Superbalist/php-event-pubsub)[![StyleCI](https://camo.githubusercontent.com/2411cf265085d994c0f51b8b879690962b242c76dd65c150b3093ceb46c390d2/68747470733a2f2f7374796c6563692e696f2f7265706f732f38303030363430382f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/80006408)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Packagist Version](https://camo.githubusercontent.com/0d8ebd45191296c257a0040bf3cf168c06b94d8bc761e795422dfb3c2cfb648d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737570657262616c6973742f7068702d6576656e742d7075627375622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/superbalist/php-event-pubsub)[![Total Downloads](https://camo.githubusercontent.com/f2cf9ac29298409509f3473a4a89c6a89e477b9a41a7e61b25f4b8039d96e95e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f737570657262616c6973742f7068702d6576656e742d7075627375622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/superbalist/php-event-pubsub)

This library builds on top of the [php-pubsub](https://github.com/Superbalist/php-pubsub) package and adds support for listening to and dispatching events over pub/sub channels.

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

[](#installation)

```
composer require superbalist/php-event-pubsub
```

Integrations
------------

[](#integrations)

Want to get started quickly? Check out some of these integrations:

- Laravel -

Usage
-----

[](#usage)

### Simple Events

[](#simple-events)

A `SimpleEvent` is an event which takes a name and optional attributes.

```
// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();
$translator = new \Superbalist\EventPubSub\Translators\SimpleEventMessageTranslator();
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator);

// dispatch an event
$event = new \Superbalist\EventPubSub\Events\SimpleEvent(
    'user.created',
    [
        'user' => [
            'id' => 1456,
            'first_name' => 'Joe',
            'last_name' => 'Soap',
            'email' => 'joe.soap@example.org',
        ],
    ]
);
$manager->dispatch('events', $event);

// dispatch multiple events
$events = [
    new \Superbalist\EventPubSub\Events\SimpleEvent(
        'user.created',
        [
            'user' => [
                // ...
            ],
        ]
    ),
    new \Superbalist\EventPubSub\Events\SimpleEvent(
        'user.created',
        [
            'user' => [
                // ...
            ],
        ]
    ),
];
$manager->dispatchBatch('events', $events);

// listen for an event
$manager->listen('events', 'user.created', function (\Superbalist\EventPubSub\EventInterface $event) {
    var_dump($event->getName());
    var_dump($event->getAttribute('user'));
});

// listen for all events on the channel
$manager->listen('events', '*', function (\Superbalist\EventPubSub\EventInterface $event) {
    var_dump($event->getName());
});
```

### Topic Events

[](#topic-events)

A `TopicEvent` is an event which takes a topic, name, version and optional attributes.

```
// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();
$translator = new \Superbalist\EventPubSub\Translators\TopicEventMessageTranslator();
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator);

// dispatch an event
$event = new \Superbalist\EventPubSub\Events\TopicEvent(
    'user',
    'created',
    '1.0',
    [
        'user' => [
            'id' => 1456,
            'first_name' => 'Joe',
            'last_name' => 'Soap',
            'email' => 'joe.soap@example.org',
        ],
    ]
);
$manager->dispatch('events', $event);

// listen for an event on a topic
$manager->listen('events', 'user/created', function (\Superbalist\EventPubSub\EventInterface $event) {
    // ...
});

// listen for an event on a topic matching the given version
$manager->listen('events', 'user/created/1.0', function (\Superbalist\EventPubSub\EventInterface $event) {
    // ...
});

// listen for all events on a topic
$manager->listen('events', 'user/*', function (\Superbalist\EventPubSub\EventInterface $event) {
    // ...
});

// listen for all events on the channel
$manager->listen('events', '*', function (\Superbalist\EventPubSub\EventInterface $event) {
    // ...
});
```

### Schema Events

[](#schema-events)

A `SchemaEvent` is an extension of the `TopicEvent` and takes a schema and optional attributes. The topic, name and version are derived from the schema.

The schema must be in the format `(protocol)://(......)?/events/(topic)/(channel)/(version).json`

```
// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();

$translator = new \Superbalist\EventPubSub\Translators\SchemaEventMessageTranslator();

$schemas = [
    'events/user/created/1.0.json' => json_encode([
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => 'My Schema',
        'type' => 'object',
        'properties' => [
            'schema' => [
                'type' => 'string',
            ],
            'user' => [
                'type' => 'object',
            ],
        ],
        'required' => [
            'schema',
            'user',
        ],
    ]),
];
$loader = new \League\JsonGuard\Loaders\ArrayLoader($schemas);

$dereferencer = new \League\JsonGuard\Dereferencer();
$dereferencer->registerLoader($loader, 'array');

$validator = new \Superbalist\EventPubSub\Validators\JSONSchemaEventValidator($dereferencer);

$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator, $validator);

// dispatch an event
$event = new \Superbalist\EventPubSub\Events\SchemaEvent(
    'http://schemas.my-website.org/events/user/created/1.0.json',
    [
        'user' => [
            'id' => 1456,
            'first_name' => 'Joe',
            'last_name' => 'Soap',
            'email' => 'joe.soap@example.org',
        ],
    ]
);
$manager->dispatch('events', $event);

// the listen expressions are the same as those used for TopicEvents.
```

### Custom Events

[](#custom-events)

You can easily use a custom event structure by writing a class which implements the `EventInterface` interface. You will then need to write a custom translator to translate incoming messages to your own event object.

Your event must implement the following methods.

```
/**
 * Return the event name.
 *
 * @return string
 */
public function getName();

/**
 * Return all event attributes.
 *
 * @return array
 */
public function getAttributes();

/**
 * Return an event attribute.
 *
 * @param string $name
 * @return mixed
 */
public function getAttribute($name);

/**
 * Set an event attribute.
 *
 * @param string|array $name
 * @param mixed $value
 */
public function setAttribute($name, $value = null);

/**
 * Check whether or not an event has an attribute.
 *
 * @param string $name
 * @return bool
 */
public function hasAttribute($name);

/**
 * Check whether or not the event matches the given expression.
 *
 * @param string $expr
 * @return bool
 */
public function matches($expr);

/**
 * Return the event in a message format ready for publishing.
 *
 * @return mixed
 */
public function toMessage();
```

Translators
-----------

[](#translators)

A translator is used to translate an incoming message into an event.

The package comes bundled with a `SimpleEventMessageTranslator`, `TopicEventMessageTranslator` and a `SchemaEventMessageTranslator`.

### Custom Translators

[](#custom-translators)

You can easily write your own translator by implementing the `MessageTranslatorInterface` interface.

Your translator must implement the following methods.

```
/**
 * @param mixed $message
 * @return null|EventInterface
 */
public function translate($message);
```

Validators
----------

[](#validators)

A validator is an optional component used to validate an event upon dispatch.

### JSONSchemaEventValidator

[](#jsonschemaeventvalidator)

This package comes bundled with a `JSONSchemaEventValidator` which works with `SchemaEvent` type events.

This validator validates events against a [JSON Schema Spec](http://json-schema.org/) using the [JSON Guard](http://json-guard.thephpleague.com/dereferencing/overview/) PHP package.

Please see the "Schema Events" section above and the JSON Guard documentation for usage examples.

### Custom Validators

[](#custom-validators)

You can write your own validator by implementing the `EventValidatorInterface` interface.

Your validator must implement the following methods.

```
/**
 * @param EventInterface $event
 * @return ValidationResult
 */
public function validate(EventInterface $event);
```

Attribute Injectors
-------------------

[](#attribute-injectors)

An attribute injector allows you to have attributes automatically injected into events when events are dispatched.

The library comes bundled with a few injectors out of the box.

- DateAttributeInjector - injects a `date` key with an ISO 8601 date time
- GenericAttributeInjector - injects a custom `key` and `value`
- HostnameAttributeInjector - injects a `hostname` key with the server hostname
- Uuid4AttributeInjector - injects a `uuid` key with a UUID-4

You can write your own injector by implementing the `AttributeInjectorInterface` or by passing a callable (which returns an array with a 'key' and 'value') to the event manager.

Your injector must implement the following methods.

```
/**
 * @return string
 */
public function getAttributeKey();

/**
 * @return mixed
 */
public function getAttributeValue();
```

Here's a usage example demonstrating both a class and a callable.

### Custom Class

[](#custom-class)

```
use Superbalist\EventPubSub\AttributeInjectorInterface;

class UserAttributeInjector implements AttributeInjectorInterface
{
    /**
     * @return string
     */
    public function getAttributeKey()
    {
        return "user";
    }

    /**
     * @return mixed
     */
    public function getAttributeValue()
    {
        return [
            'id' => 2416334,
            'email' => 'john.doe@example.org',
            'first_name' => 'John',
            'last_name' => 'Doe',
        ];
    }
}

// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();
$translator = new \Superbalist\EventPubSub\Translators\SimpleEventMessageTranslator();
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator);

$manager->addAttributeInjector(new UserAttributeInjector());

// or
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator, null, [new UserAttributeInjector()]);
```

### Callable

[](#callable)

```
// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();
$translator = new \Superbalist\EventPubSub\Translators\SimpleEventMessageTranslator();
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator);

$manager->addAttributeInjector(function () {
    return [
        'key' => 'user',
        'value' => [
            'id' => 2416334,
            'email' => 'john.doe@example.org',
            'first_name' => 'John',
            'last_name' => 'Doe',
        ],
    ];
});
```

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

[](#error-handling)

The library supports error handlers for when event translation fails, listen expression fails and validation fails.

You can pass callables into the EventManager constructor, or set them as follows:

```
// create a new event manager
$adapter = new \Superbalist\PubSub\Adapters\LocalPubSubAdapter();
$translator = new \Superbalist\EventPubSub\Translators\SimpleEventMessageTranslator();
$manager = new \Superbalist\EventPubSub\EventManager($adapter, $translator);

// hook into translation failures
$manager->setTranslateFailHandler(function ($message) {
    // the message failed to translate into an event
});

// hook into listen expression failures
$manager->setListenExprFailHandler(function (\Superbalist\EventPubSub\EventInterface $event, $expr) {
    // the event didn't match the listen expression
    // this isn't really an error, but can be useful for debug
});

// hook into validation failures
$manager->setValidationFailHandler(function (\Superbalist\EventPubSub\ValidationResult $result) {
    // the event failed validation
    var_dump($result->errors());
});
```

Examples
--------

[](#examples)

The library comes with [examples](examples) for the different types of events and a [Dockerfile](Dockerfile) for running the example scripts.

Run `make up`.

You will start at a `bash` prompt in the `/opt/php-event-pubsub` directory.

To run the examples:

```
$ php examples/SimpleEventExample.php
$ php examples/TopicEventExample.php
$ php examples/SchemaEventExample.php
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 76.7% 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 ~32 days

Recently: every ~14 days

Total

8

Last Release

3168d ago

Major Versions

1.0.0 → 2.0.02017-02-01

2.0.0 → 3.0.02017-05-16

3.0.1 → 4.0.02017-07-17

### Community

Maintainers

![](https://www.gravatar.com/avatar/8b8f533cf5a84c29d3860ee32356f0554ead023247638ea952353fc2f01b2e5d?d=identicon)[superbalist](/maintainers/superbalist)

---

Top Contributors

[![matthewgoslett](https://avatars.githubusercontent.com/u/1571743?v=4)](https://github.com/matthewgoslett "matthewgoslett (23 commits)")[![BradWhittington](https://avatars.githubusercontent.com/u/182037?v=4)](https://github.com/BradWhittington "BradWhittington (4 commits)")[![shad0wfir3](https://avatars.githubusercontent.com/u/20926935?v=4)](https://github.com/shad0wfir3 "shad0wfir3 (3 commits)")

---

Tags

event-protocolphpphp-event-pubsubphp-pubsubpubsubsuperbalist

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/superbalist-php-event-pubsub/health.svg)

```
[![Health](https://phpackages.com/badges/superbalist-php-event-pubsub/health.svg)](https://phpackages.com/packages/superbalist-php-event-pubsub)
```

###  Alternatives

[pocketmine/pocketmine-mp

A server software for Minecraft: Bedrock Edition written in PHP

3.5k74.6k86](/packages/pocketmine-pocketmine-mp)[firefly-iii/data-importer

Firefly III Data Import Tool.

7545.8k](/packages/firefly-iii-data-importer)[internal/dload

Downloads binaries.

98142.7k10](/packages/internal-dload)

PHPackages © 2026

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