如何获得Symfony对象在命令文件,如在控制器


How to get Symfony object in command file like in controller

在我的应用程序中我想执行一些维护任务。

因此,我使用cronjob运行整体维护功能。

protected function execute(InputInterface $input, OutputInterface $output)
{
   Maintenance::checkDowngradeAccounts();
}

在一个单独的命令文件中,我运行所有不同的函数。查看这里完整的命令文件:

namespace Mtr'MyBundle'Command;
use Symfony'Bundle'FrameworkBundle'Command'ContainerAwareCommand;
class Maintenance extends ContainerAwareCommand
{
    public function checkDowngradeAccounts() {
        // get downgrade accounts
        $downgrade = $this->getDoctrine()
            ->getRepository('MyBundle:Account')
            ->findAllWithDowngrade();
    }
}

只有Symfony $this对象不知道在这个文件链接在一个正常的控制器。我如何包含或获得这个容器对象?

$this与静态上下文不可用,与类依赖(通过构造函数传递)相同。您应该将调用链重构为维护实例,而不是静态调用

它是纯PHP,不涉及symfony

乌利希期刊指南。

你的例子仍然显示你静态地调用这个函数。您应该使用对象的实例来调用它,即$maintenance->checkDowngradeAccounts()

要创建适当的维护变量,您应该手动实例化它或通过DI将其作为依赖项传递。

我看到这里最简单的方法是像

class Maintenance
{
    private $doctrine;
    public function __construct(EntityManagerInterface $doctrine)
    {
        $this->doctrine = $doctrine;
    }
    public function checkDowngradeAccounts() {
        // get downgrade accounts
        $downgrade = $this->doctrine
            ->getRepository('MyBundle:Account')
            ->findAllWithDowngrade();
    }
}

命令代码(ContainerAwareCommand)已经可以访问容器,所以我们可以用它来配置Maintenance实例。

protected function execute(InputInterface $input, OutputInterface $output)
{
   $maintenance = new Maintenance($this->getContainer()->get('doctrine.orm.entity_manager');
   $maintenance->checkDowngradeAccounts();
}

为了使这个抛光,你使Maintenance成为一个服务。进一步的阅读http://symfony.com/doc/current/service_container.html