Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - How to access the service in a custom console command?

I am new to Symfony. I have created a custom command which sole purpose is to wipe demo data from the system, but I do not know how to do this.

In the controller I would do:

$nodes = $this->getDoctrine()
    ->getRepository('MyFreelancerPortfolioBundle:TreeNode')
    ->findAll();

$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
    $em->remove($node);
}
$em->flush();

Doing this from the execute() function in the command I get:

Call to undefined method ..... ::getDoctrine();

How would I do this from the execute() function? Also, if there is an easier way to wipe the data other than to loop through them and remove them, feel free to mention it.

like image 704
Magnanimity Avatar asked Oct 11 '13 15:10

Magnanimity


1 Answers

In order to be able to access the service container your command needs to extend Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.

See the Command documentation chapter - Getting Services from the Container.

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// ... other use statements

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        // ...
like image 171
Nicolai Fröhlich Avatar answered Oct 21 '22 05:10

Nicolai Fröhlich