PHP code example of spiral-packages / event-bus

1. Go to this page and download the library: Download spiral-packages/event-bus library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spiral-packages / event-bus example snippets


protected const LOAD = [
    // ...
    \Spiral\EventBus\Bootloader\EventBusBootloader::class,
];

namespace App\Bootloader;

use Spiral\EventBus\Bootloader\EventBusBootloader as BaseBootloader

class EventBusBootloader extends BaseBootloader
{
    protected const LISTENS = [
        \App\Event\UserCreated::class => [
            \App\Listener\SendWelcomeMessageListener::class
        ],
        //...
    ];
}



declare(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
    ]
];

class MyPackageBootloader extends Spiral\Boot\Bootloader\Bootloader
{
    public function start(Spiral\EventBus\ListenerRegistryInterface $registry) 
    {
        $registry->addListener(UserDeleted::class, DeleteUserComments::class);
    }
}

class UserDeleted 
{
    public function __construct(public string $name) {}
}

class DeleteUserComments 
{
    public function __construct(private CommentService $service) {}
    
    public function __invoke(UserDeleted $event)
    {
        $this->service->deleteCommentsForUser($event->name);
    }
}

use Spiral\EventBus\Attribute\Listener;

class DeleteUserComments 
{
    public function __construct(private CommentService $service) {}
    
    #[Listener]
    public function handleDeletedUser(UserDeleted $event)
    {
        $this->service->deleteCommentsForUser($event->usernname);
    }
    
    #[Listener]
    public function handleCreatedUser(UserCreated $event)
    {
        $this->service->creaateUserProfile($event->usernname);
    }
    
    #[Listener]
    public function notifyAdmins(UserCreated|UserDeleted $event)
    {
        $this->service->notifyAdmins($event->usernname);
    }
}

class DeleteUserComments implements \Spiral\EventBus\QueueableInterface
{
    // ...
}

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class UserService 
{
    public function __construct(private EventDispatcherInterface $events) {}
    
    public function deleteUserById(string $id): void
    {
        $user = User::findById($id);
        //.. 
        
        $this->events->dispatch(
            new UserDeleted($user->username)
        );
    }
}

namespace App\Bootloader;

use Spiral\EventBus\Bootloader\EventBusBootloader as BaseBootloader

class EventBusBootloader extends BaseBootloader
{
    protected const INTERCEPTORS = [
        \App\Event\Interceptor\BroadcastEventInterceptor::class,
        //...
    ];
}



declare(strict_types=1);

return [
    // ...
    'interceptors' => [
        BroadcastEventInterceptor::class
    ]
];

namespace App\Event\Interceptor;

use Spiral\Broadcasting\BroadcastInterface;

class BroadcastEventInterceptor implements \Spiral\Core\CoreInterceptorInterface
{
    public function __construct(
        private BroadcastInterface $broadcast
    ) {}
    
    public function process(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 ($event instanceof ShouldBroadcastInterface) {
            $this->broadcast->publish(
                $event->getBroadcasTopics(), 
                \json_encode($event->toBroadcast())
            );
        }
        
        return $result;
    }
}

class EventDispatcherTest extends TestCase
{
    use \Spiral\EventBus\Testing\InteractsWithEvents;

    public function testDispatchEvent(): void
    {
        $events = $this->fakeEventDispatcher();
    
        $this->getDispatcher()->dispatch(new SimpleEvent());
    
        $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();
    }
}