Search code examples
phpsymfonysymfony4symfony-messenger

How to set event name and delay time in Envelope?


I'm using symfony 4 + enqueue (https://github.com/sroze/messenger-enqueue-transport + https://packagist.org/packages/enqueue/pheanstalk) to run async jobs in beanstalk.

Right now I have:

/**
 * @var Symfony\Component\EventDispatcher\EventDispatcherInterface 
 */
private $eventDispatcher;

$event = new ArticleEvent("test title", "test description");
$this->eventDispatcher->dispatch($event, "article.publish");

But I want this job to be processed after a delay.

Documentation brings me to refactor it like:

use Enqueue\MessengerAdapter\EnvelopeItem\TransportConfiguration;
use Symfony\Component\Messenger\Envelope;

$event = new ArticleEvent("test title", "test description");
$transportConfig = (new TransportConfiguration())->setDeliveryDelay(5000);

$this->eventDispatcher->dispatch((new Envelope($event))->with($transportConfig));

The problem here is that I don't see where to place event's name (article.publish)

(Based on https://github.com/sroze/messenger-enqueue-transport#setting-custom-configuration-on-your-message)


Solution

  • With messenger you do not have "event names".

    You just need to dispatch the appropriate message instance.

    If you are publishing an article, instead of having a generic ArticleEvent class, build a PublishArticle command or an ArticlePublished event.

    The choice between the two depends on if you are registering an event (something that already happened) or a command (something you want to happen).

    Creating a handler for these messages is as simple as creating a MessageHandlerInterface implementing class:

    use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
    
    class PublishArticleHandler implements MessageHandlerInterface
    {
        public function __invoke(PublishArticle $message)
        {
            // ... do some work - like publishing the article
        }
    }