earc/observer is a ready to use and extendable psr-14 compatible observer blueprint.
$ composer require earc/observer
earc/observer uses earc/di for dependency injection.
use eArc\DI\DI;
DI::init();
Place the above code in the section where your script/framework is bootstrapped.
earc/observer does not need any configuration.
Your event has to implement the EventInterface in order to be dispatchable by the dispatcher of earc/observer.
use eArc\Observer\Interfaces\EventInterface;
use eArc\Observer\Interfaces\ListenerInterface;
class SomeEvent implements EventInterface
{
public static function getApplicableListener(): array
{
return [ListenerInterface::class];
}
}
Extend the ListenerInterface if you want to be more specific.
You can either use the observer object to register your listener
use eArc\Observer\Observer;
$observer = di_get(Observer::class);
$observer->registerListener(SomeListener::class);
or use the tagging of earc/di (if the observer instance is not build yet)
use eArc\Observer\Observer;
di_tag(Observer::class, SomeListener::class);
Hint: Tagging does not initialize the observer nor does it autoload the observer class. Both does not autoload the listener until it is called upon to process the event.
If you pass a float
as second or third argument respectively, it is interpreted as
patience. The more patience the listener has the later it is called.
use eArc\Observer\Observer;
$observer = di_get(Observer::class);
$observer->registerListener(SomeListener::class, 0.2);
or (if the observer instance is not build yet)
use eArc\Observer\Observer;
di_tag(Observer::class, SomeListener::class, -12.7);
You can unregister by
$observer->unregisterListener(SomeListener::class);
or (if the observer instance is not build yet)
use eArc\Observer\Observer;
di_clear_tags(Observer::class, SomeListener::class);
Note the different semantics of di_tag()
and di_clear_tags()
.
To dispatch your event use the dispatcher
use eArc\Observer\Dispatcher;
$dispatcher = di_get(Dispatcher::class);
$event = $dispatcher->dispatch($event);
It returns the event that may be modified by the listener.
If you want to change the behaviour of the observer you can decorate it by any
class implementing the ObserverInterface
.
use \eArc\Observer\Interfaces\ObserverInterface;
di_decorate(ObserverInterface::class, TheNewObserver::class);
Please note that every library in your project, using earc/observer, uses the
decorating class thereafter. Therefore you might be forced to write your own
dispatcher too. All you need to do is implementing the DispatcherInterface
.
- PHP ^7.2 || ^8.0
- fix patience via tag converts float to int
- documentation completed
- test coverage 100% of documented features
- fix php does not recognise ['string' => $obj, 'method'] as callable.
- added listener interface
- rewrite to be psr-14 compatible
- initial release