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