sabre-event, a simple event management library for PHP 5.4
I just released version 1.0 of sabre-event, a simple event management library for PHP, heavily inspired by both nodejs’ EventEmitter, and Igor Wielder’s Événement.
This library has a few extra features not in Événement that I really needed, and Igor had no plans adding it to his library, so I wrote my own.
In a nutshell, this is how you use it:
<?php
use Sabre\Event\EventEmitter;
include 'vendor/autoload.php';
$eventEmitter = new EventEmitter();
// subscribing
$eventEmitter->on('create', function() {
echo "Something got created, apparently\n"
});
$eventEmitter->emit('create');
?>
The EventEmitter object can also be integrated into existing objects, by extending it, or using it as a trait:
<?php
use Sabre\Event;
class MyNotUneventfulApplication implements Event\EventEmitterInterface
{
use Event\EventEmitterTrait;
}
?>
It differs from Événement in two features:
- It’s possible to prioritize listeners, and let them trigger earlier or later in the event chain.
- It’s possible for listeners to break the event chain, much like
javascript’s
preventDefault()
.
I hope it will be useful to others. You can find the full documentation on GitHub, and the preferred installation method is through Composer.
Comments
Matthew Weier O'Phinney •
Mark me as a troll if you will, but have you tried Zend\EventManager? It has the features you indicate EventEmitter has, and quite a few others... :)
Evert •
Why would you be considered a troll for that! Silly.
I looked at EventManager but it just seemed a bit too bulky for what I needed. The 1-class Événement was exactly what I was after for sabredav, but the two extra features (priorities/stopping the chain) was an absolute must.
I do need to start depending more on external packages though. I'm quite bad at it :( I always find some reason why I'd rather roll my own, but it's not really the most productive way of going about things.
Hari K T •
Nice one, something similar to Aura.Signal also http://github.com/auraphp/A...
cordoval •
thanks for sharing
Coder of Salvation •
is it possible to bind an event to a class/functionname instead of a direct implementation of the handler? and arguments? Like:
$eventEmitter->on('create', array( someObject::getInstance(), "setFoo" ) );
$eventEmitter->emit('create', array(1,2,(object)array(1,2)) );
I have a class which basically does that in a very simple way.
Nevertheless your approach seems simple and sexy as well, and if it would support the above I would definately use it.
Coder of Salvation •
the benefit of above is to have hot pluggable code, no if/else codeclutter and prevention of many lines of exception handling (inspired by Actionscript). The downside is that codeflow becomes less visible, but that can be solved by having your emitter log its emissions to a central logfile.
Evert •
Hi!
That syntax already works exactly as you described:
$emitter->on('create', [$instance, 'method']);
Coder of Salvation •
cool!