/event

Event Package

Primary LanguagePHP

League\Event by @frankdejonge

Build Status Quality Score Software License Packagist Version Total Downloads

Usage (Basic)

Register a listener for an event.

use League\Event\Emitter;

$emitter = new Emitter;
$emitter->addListener('event.name', function ($event) {
    echo "I've listened to " . $event->getName();
});

$emitter->emit('event.name');

Remove a listener.

$emitter->removeListener('event.name', $listener);
// or remove all listeners
$emitter->removeAllListeners('event.name');

Usage (Advanced)

You can create custom event types by extending the AbstractEvent class.

use League\Event\AbstractEvent;

class DomainEvent extends AbstractEvent
{
    public function getName()
    {
        return 'event.name';
    }

    // ... add business logic here
}

$emitter->emit(new DomainEvent);

You can create custom listeners.

use League\Event\AbstractEvent;
use League\Event\AbstractListener;

class DomainListener extends AbstractListener
{
    public function handle(AbstractEvent $event)
    {
        // Handle the event.
    }
}

You can stop event propagation.

$emitter->addListener('event', function ($event) {
    $event->stopPropagation();
});
$emitter->addListener('event', function ($event) {
    // This will never be called!
});

$emitter->emit('event');

You can prioritize listeners by using the PriorityEmitter.

$emitter = new League\Event\PriorityEmitter;
$emitter->addListener('event', $second, 10); // This will be handled
$emitter->addListener('event', $first, 50); // after this is handled.
$emittedEvent = $emitter->emit('event');

Passing additional parameters to event listeners

When emitting an event, all trailing arguments will be forwarded to the listeners. Due to how php's interfaces work a default value must be supplied when present in the handle method signature to ensure method signature compatibility.

Using a closure

$emitter->on('event', function ($event, $param = null) {
	var_dump(func_get_args());
});

$emitter->emit('event', 'param value');

Using a class

class Listener extends AbstractListener
{
	public function handle(AbstractEvent $event, $param = null)
	{
		var_dump(func_get_args());
	}
}

$emitter->on('event', new Listener);
$emitter->emit('event', 'param value');