php – Symfony2 – 如何在自定义控制台命令中访问该服务?

我是Symfony的新手.我创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何执行此操作.

在控制器中我会这样做:

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

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

从我得到的命令中的execute()函数执行此操作:

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

我如何从execute()函数执行此操作?此外,如果有一种更简单的方法来擦除数据而不是循环它们并删除它们,请随意提及.

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

请参阅命令文档章节 – 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();
        // ...

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...