Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active October 2, 2022 12:58
Show Gist options
  • Save ismail1432/14a08740faf2e3f368d0cd69fb2a5234 to your computer and use it in GitHub Desktop.
Save ismail1432/14a08740faf2e3f368d0cd69fb2a5234 to your computer and use it in GitHub Desktop.
<?php
use Symfony\Component\Messenger\MessageBusInterface;
final class Bus
{
// The trait contains a `handle` method
// that dispatch the message and return the result.
use Symfony\Component\Messenger\HandleTrait;
private MessageBusInterface $messageBus;
/**
* @var iterable<PreHandlerInterface>
* All classes that implements PreHandlerInterface
*/
private iterable $preHandlers;
/**
* @var iterable<PostHandlerInterface>
* All classes that implements PostHandlerInterface
*/
private iterable $postHandlers;
public function __construct(
iterable $preHandlers,
iterable $postHandlers,
MessageBusInterface $messageBus) {
$this->preHandlers = $preHandlers;
$this->postHandlers = $postHandlers;
$this->messageBus = $messageBus;
}
public function dispatch(object $message)
{
// We iterate on each instance of `PreHandlerInterface`
// and check if the message is supported
// if yes, we call `preHandle`
/** @var PreHandlerInterface $preHandler */
foreach ($this->preHandlers as $preHandler) {
if ($preHandler->supports($message)) {
$preHandler->preHandle($message);
}
}
// We dispatch the message so it's handle by the handler
$result = $this->handle($message);
// We iterate on each instance of `PostHandlerInterface`
// and check if the message is supported
// if yes, we call `postHandle` with the $message and the $result as argument
/** @var PostHandlerInterface $postHandler */
foreach ($this->postHandlers as $postHandler) {
if ($postHandler->supports($message)) {
$postHandler->postHandle($message, $result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment