11

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.

4

2 回答 2

16

为了能够访问服务容器,您的命令需要扩展Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand

请参阅命令文档章节 -从容器获取服务

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();
        // ...
于 2013-10-11T15:51:55.620 回答
15

Symfony 3.3(2017 年 5 月)开始,您可以轻松地在命令中使用依赖注入。

只需在您的: 中使用PSR-4 服务自动发现services.yml

services:
    _defaults:
        autowire: true

    App\Command\:
        resource: ../Command

然后使用常见的构造函数注入,最后甚至Commands会有干净的架构:

final class MyCommand extends Command
{
    /**
     * @var SomeDependency
     */
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;

        // this is required due to parent constructor, which sets up name 
        parent::__construct(); 
    }
}

自Symfony 3.4(2017 年 11 月)以来,这将(或已经这样做,取决于阅读时间)成为标准,届时命令将被延迟加载

于 2017-09-01T19:51:41.220 回答