Symfony Console in a laminas app - how to get instance of console output in laminas factory

114 Views Asked by At

I have a laminas app that is using the symfony console as a cli. I have a complex service that sends information via events. I would like the output of the console to be a subscriber of the event, so that event information can be written to the console output. At the moment, it just sends information to stdout, which is displayed in the console, but i would like to use the functionality (and formatting) of the Output inside an event listener.

May be easier to understand with an example:

class MyCliCommand extends Command
{
    public function __construct(private ComplexService $service){}
    protected function execute(InputInterface $input, OutputInterface $output){
        $this->complexService->doComplexThings();
        $output->writeln("\n Cli complete");
        return Command::SUCCESS;
    }

}

class MyCliCommandFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null){
        $complexService = $container->get(ComplexService::class);
        $complexService->attach($container->get(DbLogger::class));
        $complexService->attach($container->get(EmailNotifier::class));
        $complexService->attach($container->get(CliOutputFormatter::class)); //***** can i get the Output instance from the Command somehow?
        return new MyCliCommand($complexService);
    }
}
1

There are 1 best solutions below

0
Vasil Dakov On

I think you can do that. One possible solution is to inject the EventManager in your cli command:

class MyCliCommand extends Command
{
    public function __construct(
        private ComplexService $service,
        private EventManager $eventManager,
    ){ }

    protected function execute(
        InputInterface $input, 
        OutputInterface $output
    ) {
        // ... you code

        // use the params array to pass your data to the listener
        $params = []; 

        // trigger the event and pass your params
        $this->eventManager->trigger(__FUNCTION__, $this, $params);
    }
}

I hope this will help.