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.
Since Symfony 3.3 (May 2017) you can use Dependency Injection in commands with ease.
Just use PSR-4 services autodiscovery in your
services.yml
:Then use common Constructor Injection and finally even
Commands
will have clean architecture:This will (or already did, depends of time reading) become standards since Symfony 3.4 (November 2017), when commands will be lazy loaded.
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.