- Notifications
You must be signed in to change notification settings - Fork2
A simple observer pattern implementation based on symfony event handler for Spiral Framework 2.x, allowing you to subscribe and listen for various events that occur within your application.
License
spiral-packages/event-bus
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Subscribe and listen for various events that occur within your application.
Make sure that your server is configured with following PHP version and extensions:
- PHP 8.0+
- Spiral framework 2.9+
You can install the package via composer:
composer require spiral-packages/event-bus
After package install you need to register bootloader from the package.
protectedconstLOAD = [// ... \Spiral\EventBus\Bootloader\EventBusBootloader::class,];
or
namespaceApp\Bootloader;useSpiral\EventBus\Bootloader\EventBusBootloaderasBaseBootloaderclass EventBusBootloaderextends BaseBootloader{protectedconstLISTENS = [ \App\Event\UserCreated::class => [ \App\Listener\SendWelcomeMessageListener::class ],//... ];}
At first need create config fileapp/config/event-bus.php, where you can specify listeners.
<?phpdeclare(strict_types=1);return ['queueConnection' =>env('EVENT_BUS_QUEUE_CONNECTION'),// default queue connection for Listeners with \Spiral\EventBus\QueueableInterface'discoverListeners' =>env('EVENT_BUS_DISCOVER_LISTENERS',true),// Discover listeners with \Spiral\EventBus\Attribute\Listener attribute'listeners' => [ UserDeleted::class => [ DeleteUserComments::class, ] ],'interceptors' => [ BroadcastEventInterceptor::class ]];
You can also register listeners viaSpiral\EventBus\ListenerRegistryInterface
class MyPackageBootloaderextendsSpiral\Boot\Bootloader\Bootloader{publicfunctionstart(Spiral\EventBus\ListenerRegistryInterface$registry) {$registry->addListener(UserDeleted::class, DeleteUserComments::class); }}
class UserDeleted {publicfunction__construct(publicstring$name) {}}
Make sure to use variable
$eventfor event handler method. It's required.
class DeleteUserComments {publicfunction__construct(privateCommentService$service) {}publicfunction__invoke(UserDeleted$event) {$this->service->deleteCommentsForUser($event->name); }}
If you are using listeners with attributes'discoverListeners' = true, you don't need to register them, they will beregistered automatically.
useSpiral\EventBus\Attribute\Listener;class DeleteUserComments {publicfunction__construct(privateCommentService$service) {} #[Listener]publicfunctionhandleDeletedUser(UserDeleted$event) {$this->service->deleteCommentsForUser($event->usernname); } #[Listener]publicfunctionhandleCreatedUser(UserCreated$event) {$this->service->creaateUserProfile($event->usernname); } #[Listener]publicfunctionnotifyAdmins(UserCreated|UserDeleted$event) {$this->service->notifyAdmins($event->usernname); }}
If you want to push listener to a queue, you can addSpiral\EventBus\QueueableInterface
class DeleteUserCommentsimplements \Spiral\EventBus\QueueableInterface{// ...}
useSymfony\Component\EventDispatcher\EventDispatcherInterface;class UserService {publicfunction__construct(privateEventDispatcherInterface$events) {}publicfunctiondeleteUserById(string$id):void {$user = User::findById($id);//..$this->events->dispatch(newUserDeleted($user->username) ); }}
The package provides convenient Bootloader to configure coreinterceptorsSpiral\EventBus\Bootloader\EventBusBootloader automatically:
namespaceApp\Bootloader;useSpiral\EventBus\Bootloader\EventBusBootloaderasBaseBootloaderclass EventBusBootloaderextends BaseBootloader{protectedconstINTERCEPTORS = [ \App\Event\Interceptor\BroadcastEventInterceptor::class,//... ];}
or via configapp/config/event-bus.php
<?phpdeclare(strict_types=1);return [// ...'interceptors' => [ BroadcastEventInterceptor::class ]];
namespaceApp\Event\Interceptor;useSpiral\Broadcasting\BroadcastInterface;class BroadcastEventInterceptorimplements \Spiral\Core\CoreInterceptorInterface{publicfunction__construct(privateBroadcastInterface$broadcast ) {}publicfunctionprocess(string$eventName,string$action, array ,CoreInterface$core):mixed {$event =$parameters['event'];// Event object$listeners =$parameters['listeners'];// array of invokable listeners$result =$core->callAction($eventName,$action,$parameters);if ($eventinstanceof ShouldBroadcastInterface) {$this->broadcast->publish($event->getBroadcasTopics(),\json_encode($event->toBroadcast()) ); }return$result; }}
composertestIf you are usingspiral/testing package in your application, you can additionallyuse traitSpiral\EventBus\Testing\InteractsWithEvents in your tests cases.
class EventDispatcherTestextends TestCase{use \Spiral\EventBus\Testing\InteractsWithEvents;publicfunctiontestDispatchEvent():void {$events =$this->fakeEventDispatcher();$this->getDispatcher()->dispatch(newSimpleEvent());$events->assertListening(SimpleEvent::class, SimpleListener::class);$events->assertListening(SimpleEvent::class, ListenerWithAttributes::class,'methodA');$events->assertDispatched(SimpleEvent::class)$events->assertDispatched(SimpleEvent::class,function(SimpleEvent$event) {return$event->someProperty ==='foo'; });$events->assertDispatchedTimes(SimpleEvent::class,10);$events->assertNotDispatched(AnotherSimpleEvent::class);$events->assertNotDispatched(AnotherSimpleEvent::class);$events->assertNothingDispatched(); }}
Please seeCHANGELOG for more information on what has changed recently.
Please seeCONTRIBUTING for details.
Please reviewour security policy on how to report security vulnerabilities.
The MIT License (MIT). Please seeLicense File for more information.
About
A simple observer pattern implementation based on symfony event handler for Spiral Framework 2.x, allowing you to subscribe and listen for various events that occur within your application.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.