Search code examples
phpsymfonysymfony4

Injecting services into a CLI Symfony 4 App


I've got a Symfony 4.2 app with a CLI script, calling a Command - which works just fine.

But in my command I'm trying to access the DB (via Doctrine).

The documentation suggests that I can just add a constructor to my Command with what I need and it'll get injected. Except, it's my code constructing the Command when I call:

$applicant->add(new \App\Command\MyCommand());

If I need to inject it, that's fine, but how do I get access to the service from my CLI script in that case?


Solution

  • Please read documentation https://symfony.com/doc/current/console.html

    Registering the Command Symfony commands must be registered as services and tagged with the console.command tag. If you're using the default services.yaml configuration, this is already done for you, thanks to autoconfiguration.

    Executing the Command After configuring and registering the command, you can execute it in the terminal:

    php bin/console app:create-user As you might expect, this command will do nothing as you didn't write any logic yet. Add your own logic inside the execute() method.

    As you can see you can later call your commands via bin/console. For command to have access to database you need to inject specific service, Im not in fan of injecting whole container, but here is an example for you Symfony 4: doctrine in command