Spiffy\Event is a light-weight, HHVM compatible, and dependency free event library.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
test
.gitignore
.scrutinizer.yml
.travis.yml
LICENSE.md
README.md
composer.json

README.md

Spiffy\Event

Build Status Code Coverage Scrutinizer Code Quality

Installation

Spiffy\Event can be installed using composer which will setup any autoloading for you.

composer require spiffy/spiffy-event

Additionally, you can download or clone the repository and setup your own autoloading.

Create an event

use Spiffy\Event\Event;

// Create an event that fires on 'foo'
$event = new Event('foo');

// Creates an event with a target
$event = new Event('foo', 'target');
$event->getTarget(); // 'target'

// Event can have parameters too
$event = new Event('foo', 'target', ['foo' => 'bar']);
$event->getParams()['foo']; // 'bar'

Listening to events

use Spiffy\Event\EventManager;

$em = new EventManager();

// Listen with a priority of 1
$em->on('foo', function() { echo 'a'; }, 1);

// Listen with a higher priority
$em->on('foo', function() { echo 'b'; }, 10);

// Event default with priority 0
$em->on('foo', function() { echo 'c'; });
$em->on('foo', function() { echo 'd'; });

// echos 'bacd'

Firing events

use Spiffy\Event\Event;
use Spiffy\Event\EventManager;

$em = new EventManager();
$em->on('foo', function() { echo 'fired'; });

// Simplest form of fire requiring just the type
$em->fire('foo'); // fired

// You can also specify the target and params when using the type
$em->fire('foo', 'target', ['foo' => 'bar']);

// You can also provide your own event.
// This is identical to the fire above.
$event = new Event('foo', 'target', ['foo' => 'bar']);
$em->fire($event);

Handling responses

use Spiffy\Event\Event;
use Spiffy\Event\EventManager;

$em = new EventManager();

// Respones are returned as a SplQueue (FIFO).
$em->on('foo', function() { return 'a'; });
$em->on('foo', function() { return 'b'; });

// Outputs 'ab'
foreach ($em->fire('foo') as $response) {
    echo $response;
}

Plugins

Sometimes you may want to collect several on() calls in a single class. Spiffy\Event provides a Plugin interface you can implement and pass to the plug() method to prepare several events at a time. The name plugin is used because a collection of events is generally used to plugin additional functionality to an object.

use Spiffy\Event\Event;
use Spiffy\Event\Plugin;

class MyPlugin implements Plugin
{
    public function plug(Manager $events)
    {
        $events->on('foo', [$this, 'onFoo']);
    }

    public function onFoo(Event $e)
    {
        echo 'do foo';
    }
}

$em = new EventManager();
$em->attach(new MyPlugin());

// output is 'do foo'
$em->fire('foo');