spiffy / spiffy-event
Spiffy\Event is a light-weight, HHVM compatible, and dependency free event library.
Installs: 21 324
Dependents: 3
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ~4.0
- squizlabs/php_codesniffer: ~1.0
This package is not auto-updated.
Last update: 2019-02-20 17:53:57 UTC
README
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');