Last Updated: February 25, 2016
·
16.56K
· pleone

Symfony2 Call Service from Command

Normally ( in controllers ) to use DIC and call a service you use:

$this->get('service')

But if you want to call a service in a class that extends Command ( Symfony\Component\Console\Command\Command ) you have to use this:

$this->getApplication()->getKernel()->getContainer()->get('service');

3 Responses
Add your response

You can also use extend the ContainerAwareCommand:

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class FooCommand extends ContainerAwareCommand
{
    // ...
}

Then you can use:

$this->get('service);
over 1 year ago ·

Into Symfony 2.3.7
$em = $this->getContainer()->get('doctrine.orm.entity_manager');

over 1 year ago ·

You can also just decouple your commands from Symfony and use them as services, then you can do a regular dependecy injection to the constructor of the command.

over 1 year ago ·