charm/event

A simple event emitter interface and a trait with the methods 'on', 'off' and 'emit'.

1.0.0 2021-09-14 14:25 UTC

This package is auto-updated.

Last update: 2024-11-18 08:36:35 UTC


README

Microscopic event emitter implementation. An interface and a trait that provides the methods:

  • EventEmitterInterface::on( string $eventName, callable $handler )
  • EventEmitterInterface::off( string $eventName, callable $handler = ? )
  • EventEmitterInterface::emit( string $eventName, object $data, bool $cancelable=true )

To allow "hooks" style functionality, a StaticEventEmitterTrait is provided, which creates a static method StaticEventEmitterTrait::events(): EventEmitterInterface method. This way you can listen to events on a class level (instead of on a per-instance basis).

Events that are being processed via EventEmitterInterface::emit can be cancelled by setting the property 'cancelled' to a "truthy value".

Complete example

<?php
require("vendor/autoload.php");

class Example implements Charm\Event\EventEmitterInterface {
    use Charm\Event\EventEmitterTrait;

    const SAMPLE_EVENT = 'Example::SAMPLE_EVENT';

}

$instance = new Example();

// First handler
$instance->on(Example::SOME_EVENT, function($data) {
    echo "Got: ".$data->message."\n"; 
    $data->cancelled = true;
});

// Second handler won't run because the first handler set `$data->cancelled` to true
$instance->on(Example::SOME_EVENT, function($data) {
    echo "No message for me\n";
});

$instance->emit(Example::SOME_EVENT, $data = (object) [ 'message' => 'OK' ]);

Best Practices

There really aren't many best practices. Use this however you want. I like to declare a constant named by class name and constant name, like in the example.