微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();
        // ...

原文地址:https://www.jb51.cc/php/138335.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐