Create a symfony console command and DI (autowiring) of service in the command

153 Views Asked by At

I want to create a symfony console command that list the listeners subscribed to the doctrine event dispatcher. something like symfony console app:debug-doctrine-dispatcher.

For that I need access from my command execute method to the doctrine.dbal.event_manager service. I can't manage to autowire Symfony\Bridge\Doctrine\ContainerAwareEventManager (doctrine.dbal.event_manager):

Cannot autowire service "App\Command\DebugDoctrineDispatcher": argument "$manager" of method "__construct()" references class "Symfony\Bridge\Doctrine\ContainerAwareEventManager" but no such service  
   exists. You should maybe alias this class to the existing "doctrine.dbal.default_connection.event_manager" service.

When I want to alias this service:

services:
    doctrine.dbal.default_connection.event_manager:
        alias: 'Doctrine\Common\EventManager'

I got a error too:

  You have requested a non-existent service "doctrine.dbal.default_connection.event_manager".  

The posts I've found mention autowiring and DI in __construct method of the command like other services.

Here is my command code:

<?php

namespace App\Command;

use Symfony\Bridge\Doctrine\ContainerAwareEventManager;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand('app:debug-doctrine-dispatcher')]
class DebugDoctrineDispatcher extends Command
{
    public function __construct(
        private ContainerAwareEventManager $manager,
        string $name = null
    )
    {
        parent::__construct($name);
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
    // TODO: Change the autogenerated stub
        $output->writeln([
        'Entity Listeners and Events Subscribers registered in Doctrine dispatcher',
        '============',
        '',
    ]);

        $o = print_r($this->manager->getAllListeners(), true);
        $output->writeln($o);

        //parent::execute($input, $output);
        return Command::SUCCESS;
    }
}

Can you enlight me?

Thanks a lot!

0

There are 0 best solutions below