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');
Written by pleone
Related protips
3 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#