在我的 Symfony 命令中调用一个 repo 方法


Call a repo method in my Symfony command

我是大三学生,我正在学习Symfony2,我的问题是:

我有一个带有方法的存储库类,我想在我的命令类中调用此方法。我该怎么做?

这是存储库方法:

public function findAllStatusToDo(Library $library = null)
{
    $qb = $this->createQueryBuilder('l');
    $qb->select('l, COUNT(l) licenses')
        ->andWhere("l.status = :status")
        ->setParameter(':status', XMLReport::STATUS_ToDo)
        ->addGroupBy('l.library')
        ->addGroupBy('l.isbn');
    if ($library instanceof Library) {
        $qb->andWhere("l.library = :library")->setParameter(':library', $library->getCode());
    }
    return $qb->getQuery()->getResult();
}

这是命令类:

class GenerateXMLCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('reports:generateXML')
            ->setDescription('Generate XML');
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    }
}

谢谢。

execute() 命令中,您只需从容器中获取doctrine服务,然后像这样调用存储库方法:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $container  = $this->getContainer();
    $em         = $container->get('doctrine')->getManager();
    $statusToDo = $em->getRepository('AppBundle:MyRepository')->findAllStatusToDo();
}

只需确保调用正确的存储库来代替上述代码中的AppBundle:MyRepository即可。