weew/eventer

Simple event system.

v2.2.2 2016-07-21 11:17 UTC

This package is not auto-updated.

Last update: 2024-12-21 21:19:54 UTC


README

Build Status Code Quality Test Coverage Version Licence

Table of contents

Installation

composer install weew/eventer

Usage

This event system allows you to easily subscribe to certain events and get notified as soon as one occurs. The most simple way to subscribe to an event is by using a string as the event name.

Simple subscription

The easiest way to create a subscription is to use callback function.

$eventer = new Eventer();
$eventer->subscribe('event.name', function(IEvent $event) {
    echo $event->getName();
    // event.name
});
$eventer->dispatch('event.name');

Attaching data to an event

Mostly you want to throw an event with particular data attached. The quickest way to achieve this is to use the generic events.

$eventer = new Eventer();
$eventer->subscribe('event.name', function(IEvent $event) {
    var_dump($event->getData());
    // ['secret' => 'secret value']
    echo $event->get('secret');
    // secret value
});

$event = new GenericEvent('event.name', ['secret' => 'secret value']);
// or
$event = new GenericEvent('event.name');
$event->set('secret', 'secret value');

$eventer->dispatch($event);

Creating custom events

In more complex applications I would suggest to roll your own events. This makes the code much more easier to understand since you'll never have to guess what the event name might be. It also allows you to extend your events with more complex behaviour.

class CustomEvent extends Event {
    public function getSecret() {
        return 'secret value';
    }
}

$eventer = new Eventer();
$eventer->subscribe(CustomEvent::class, function(CustomEvent $event) {
    echo $event->getSecret();
    // secret value
});

$eventer->dispatch(new CustomEvent());

Unsubscribing from events

To unsubscribe from an event you can simply pass the subscription object to the unsubscribe method on the event dispatcher.

$eventer = new Eventer();
$subscription = $eventer->subscribe('event.name', 'abstract.value');
$eventer->unsubscribe($subscription);

Event subscribers

Using callbacks in your events might not always be an optimal solution. Therefore you can create event subscriber classes that get called whenever an event occurs. The class must have the handle(IEvent $event) method, but there is no specific interface that you are forced to implement.

class CustomEvent extends Event {
    public function getSecret() {
        return 'secret value';
    }
}

class CustomEventSubscriber {
    public function handle(IEvent $event) {
        /** @var CustomEvent $event */
        echo $event->getSecret();
        // secret value
    }
}

$eventer = new Eventer();
$eventer->subscribe(CustomEvent::class, CustomEventSubscriber::class);
$eventer->dispatch(new CustomEvent());

Existing container integrations

There is an integration for the weew/container. See eventer-container-aware.