gtk3tw
Last Updated: February 25, 2016
·
9.893K
· pleone
Bug

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');
Say Thanks
Respond

3 Responses
Add your response

1333
10dfb9071cea4272eabdfb91d18f377f

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 ·
10867
8f4d8e233b57941c8e80aa3d1ceef722

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

over 1 year ago ·
15864

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 ·