Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

PSR-14 event dispatcher

License

NotificationsYou must be signed in to change notification settings

yiisoft/event-dispatcher

Yii

Yii Event Dispatcher


Latest Stable VersionTotal DownloadsBuild StatusCode CoverageMutation testing badgestatic analysistype-coverage

PSR-14 compatible event dispatcher provides an ability to dispatch events and listento events dispatched.

Features

  • PSR-14 compatible.
  • Simple and lightweight.
  • Encourages designing event hierarchy.
  • Can combine multiple event listener providers.

Requirements

  • PHP 8.0 or higher.

Installation

The package could be installed withComposer:

composer require yiisoft/event-dispatcher

General usage

Note: For usage with Yii3 seeyiisoft/yii-event andthe guide.

The library consists of two parts: event dispatcher and event listener provider. Provider's job is to register listenersfor a certain event type. Dispatcher's job is to take an event, get listeners for it from a provider and call them sequentially.

// Add some listeners.$listeners = (new \Yiisoft\EventDispatcher\Provider\ListenerCollection())    ->add(function (AfterDocumentProcessed$event) {$document =$event->getDocument();// Do something with document.    });$provider =newYiisoft\EventDispatcher\Provider\Provider($listeners);$dispatcher =newYiisoft\EventDispatcher\Dispatcher\Dispatcher($provider);

The event dispatching may look like:

usePsr\EventDispatcher\EventDispatcherInterface;finalclass DocumentProcessor{privateEventDispatcherInterface$eventDispatcher;publicfunction__construct(EventDispatcherInterface$eventDispatcher) {$this->eventDispatcher =$eventDispatcher;    }publicfunctionprocess(Document$document):void    {// Process the document, then dispatch completion event.$this->eventDispatcher->dispatch(newAfterDocumentProcessed($document));    }}

Stoppable events

Event could be made stoppable by implementingPsr\EventDispatcher\StoppableEventInterface:

finalclass BusyEventimplementsPsr\EventDispatcher\StoppableEventInterface{// ...publicfunctionisPropagationStopped():bool    {returntrue;    }}

This way we can ensure that only first event listener will be able to handle the event. Another option isto allow stopping propagation in one of the listeners by providing corresponding event method.

Events hierarchy

Events do not have any name or wildcard matching on purpose. Event class names and class/interface hierarchyand composition could be used to achieve great flexibility:

interface DocumentEvent{}finalclass BeforeDocumentProcessedimplements DocumentEvent{}finalclass AfterDocumentProcessedimplements DocumentEvent{}

With the interface above listening to all document-related events could be done as:

$listeners->add(staticfunction (DocumentEvent$event) {// log events here});

Combining multiple listener providers

In case you want to combine multiple listener providers, you can useCompositeProvider:

$compositeProvider =newYiisoft\EventDispatcher\Provider\CompositeProvider();$provider =newYiisoft\EventDispatcher\Provider\Provider($listeners);$compositeProvider->add($provider);$compositeProvider->add(newclassimplements ListenerProviderInterface {publicfunctiongetListenersForEvent(object$event):iterable    {yieldstaticfunction ($event) {// handle        };    }});$dispatcher =newYiisoft\EventDispatcher\Dispatcher\Dispatcher($compositeProvider);

Register listeners with concrete event names

You may use a more simple listener provider, which allows you to specify which event they can provide.

It can be useful in some specific cases, for instance if one of your listeners does not need the eventobject passed as a parameter (can happen if the listener only needs to run at a specific stage duringruntime, but does not need event data).

In that case, it is advised to use the aggregate (see above) if you need features from both providers includedin this library.

$listeners = (new \Yiisoft\EventDispatcher\Provider\ListenerCollection())    ->add(staticfunction () {// this function does not need an event object as argument}, SomeEvent::class);

Dispatching to multiple dispatchers

There may be a need to dispatch an event via multiple dispatchers at once. It could be achieved like the following:

useYiisoft\EventDispatcher\Dispatcher\CompositeDispatcher;useYiisoft\EventDispatcher\Dispatcher\Dispatcher;useYiisoft\EventDispatcher\Provider\ListenerCollection;useYiisoft\EventDispatcher\Provider\Provider;// Add some listeners.$listeners1 = (newListenerCollection())    ->add(function (AfterDocumentProcessed$event) {$document =$event->getDocument();// Do something with document.    });$provider1 =newProvider($listeners1);// Add some listeners.$listeners2 = (newListenerCollection())    ->add(function (AfterDocumentProcessed$event) {$document =$event->getDocument();// Do something with document.    });$provider2 =newProvider($listeners2);$dispatcher =newCompositeDispatcher();$dispatcher->attach(newDispatcher($provider1));$dispatcher->attach(newDispatcher($provider2));$dispatcher->dispatch(newMyEvent());

Documentation

If you need help or have a question, theYii Forum is a good place for that.You may also check out otherYii Community Resources.

License

The Yii Event Dispatcher is free software. It is released under the terms of the BSD License.Please seeLICENSE for more information.

Maintained byYii Software.

Credits

  • Larry Garfield (@crell) for initial implementation of deriving callable parameter type.

Support the project

Open Collective

Follow updates

Official websiteTwitterTelegramFacebookSlack

Sponsor this project

  •  

Contributors20

Languages


[8]ページ先頭

©2009-2025 Movatter.jp