Categories
PHP

Using a Symfony Console Command from within a Symfony Messenger MessengerHandler

Imagine having a console command you use for cron jobs. And you would like to use that command when handling queued messages from the Symfony Messenger.

How to solve this?

<?php

namespace App\Messenger\MessageHandler;

use App\Command\MyCommand;
use App\Messenger\Message\MyMessage;
use Exception;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class MyMessageHandler implements MessageHandlerInterface
{
    /** @var Application */
    protected $application;

    /**
     * MyMessageHandler constructor.
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        $this->application = new Application($kernel);
        $this->application->setAutoExit(false);
    }

    /**
     * @param MyMessage $myMessage
     * @throws Exception
     */
    public function __invoke(MyMessage $myMessage)
    {
        $command = $this->application->find(MyCommand::getDefaultName());

        $input = new ArrayInput([
            '--id' => $myMessage->getId(),
        ]);
        $output = new NullOutput();

        $command->run($input, $output);
    }
}

Further reading

Symfony Console Commands

Symfony Messenger

Leave a Reply

Your email address will not be published. Required fields are marked *