加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 13:41:41 所属栏目:PHP教程 来源:网络整理
导读:我是Symfony的新手.我创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何执行此操作. 在控制器中我会这样做: $nodes = $this-getDoctrine() -getRepository('MyFreelancerPortfolioBundle:TreeNode') -findAll();$em = $this-getDoctri
我是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()函数执行此操作?此外,如果有一种更简单的方法来擦除数据而不是循环它们并删除它们,请随意提及.

为了能够访问服务容器,您的命令需要扩展 SymfonyBundleFrameworkBundleCommandContainerAwareCommand.

请参阅命令文档章节 – Getting Services from the Container.

use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
// ... other use statements

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input,OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        // ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读