From 66a0825bd74a800f754e218d3843a8ffbc2ddffe Mon Sep 17 00:00:00 2001 From: Anton Ukhanev Date: Sat, 11 Apr 2020 11:24:28 +0200 Subject: [PATCH] Add usage examples to readme --- README.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 84ded0e..9296a04 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,65 @@ ## Details The [PSR-14][] standard provides interfaces used for dispatching events. But what of events themselves? How can a consumer of the dispatcher (i.e. the emitter) interoperate with the handler, if they have no agreement -on what an event may look like? +on what an event may look like? This package aims to provide interfaces that could facilitate the interoperability +of events that are identified by event name. + +## Usage +### Basic Features +In essence, an event is but a map of parameters associated with a name. + +```php +make('my_event', ['key' => 'value']); +echo $event->getName(); // 'my_event' +echo $event->getParam('key'); // 'value' + +$params = $event->getParams(); +var_dump($params); // ['key' => 'value'] + +$params['hello'] = 'world'; +$event->setParams($params); +echo $event->getParam('hello'); // 'world' +?> +``` + +### With PSR-14 +Evemts cam be dispatched using a standards-compliant event dispatcher. +This example requires the already included [`dhii/event-dispatcher-interface`][] package. +```php +addListener('my_event', function (EventInterface $event) { + $params = $event->getParams(); + $params['key'] = 'other_value'; + $event->setParams($params); + $event->stopPropagation(); +}, 1); + +// Second listener is never run, therefore the value does not change again +$listenerMap->addListener('my_event', function (EventInterface $event) { + $params = $event->getParams(); + $params['key'] = 'yet another value'; + $event->setParams($params); +}, 2); + +$event = $factory->make('my_event', ['key' => 'value']); +$dispatcher->dispatch($event); +echo $event->getParam('key'); // 'other_value' +?> +``` [PSR-14]: https://www.php-fig.org/psr/psr-14/ +[`dhii/event-dispatcher-interface`]: https://packagist.org/packages/dhii/event-dispatcher-interface