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

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

NotificationsYou must be signed in to change notification settings

spiral-packages/event-bus

Repository files navigation

PHPLatest Version on PackagistGitHub Tests Action StatusTotal Downloads

Subscribe and listen for various events that occur within your application.

Requirements

Make sure that your server is configured with following PHP version and extensions:

  • PHP 8.0+
  • Spiral framework 2.9+

Installation

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        ],//...    ];}

Usage

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);    }}

Event example

class UserDeleted {publicfunction__construct(publicstring$name) {}}

Listener example

Make sure to use variable$event for event handler method. It's required.

class DeleteUserComments {publicfunction__construct(privateCommentService$service) {}publicfunction__invoke(UserDeleted$event)    {$this->service->deleteCommentsForUser($event->name);    }}

Listener example with attributes

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);    }}

Listener example that should be handled in a queue

If you want to push listener to a queue, you can addSpiral\EventBus\QueueableInterface

class DeleteUserCommentsimplements \Spiral\EventBus\QueueableInterface{// ...}

Event dispatching

useSymfony\Component\EventDispatcher\EventDispatcherInterface;class UserService {publicfunction__construct(privateEventDispatcherInterface$events) {}publicfunctiondeleteUserById(string$id):void    {$user = User::findById($id);//..$this->events->dispatch(newUserDeleted($user->username)        );    }}

Interceptors

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;    }}

Testing

composertest

If 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();    }}

Changelog

Please seeCHANGELOG for more information on what has changed recently.

Contributing

Please seeCONTRIBUTING for details.

Security Vulnerabilities

Please reviewour security policy on how to report security vulnerabilities.

Credits

License

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

Stars

Watchers

Forks

Contributors3

  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp