覆盖Symfony 对 Command.php组件控制台



我正在symfony2应用程序上开发某种cronjob监视。

我创建了一个带有'completed'属性的commandexexecution实体。

我正在使用控制台事件来创建和保存这个实体。

我的服务:

kernel.listener.console:
        class: EvoCronBundleEventListenerConsoleListener
        arguments: [@doctrine.orm.entity_manager]
        tags:
            - { name: kernel.event_listener, event: console.command, method: onConsoleCommand }
            - { name: kernel.event_listener, event: console.terminate, method: onConsoleTerminate }
            - { name: kernel.event_listener, event: console.exception, method: onConsoleException }

和当命令开始和结束执行时调用的ConsoleListener:onConsoleCommand()和ConsoleListener:onConsoleTerminate()方法:

public function onConsoleCommand(ConsoleCommandEvent $event)
{
    $command = $event->getCommand();
    $commandEntity = $this->em->getRepository('EvoCronBundle:Command')->findOneBy(['name' => $command->getName()]);
    $commandExecution = new CommandExecution();
    $commandExecution->setCommand($commandEntity);
    $this->em->persist($commandExecution);
    $this->em->flush();
    // here I want to pass my entity to the command, so I can get it back in the onConsoleTerminate() method
    $command->setCommandExecution($commandExecution);
}
public function onConsoleTerminate(ConsoleTerminateEvent $event)
{
    $command = $event->getCommand();
    // here, retrieve the commandExecution entity passed in onConsoleCommand() method
    $commandExecution = $command->getCommandExecution();
    $commandExecution->setCompleted(true);
    $this->em->flush();
}

正如你在这些方法中所看到的,我想添加一个commandexexecution属性到Symfony组件控制台CommandCommand.php,这样我就可以传入我的commandexexecution实体并改变它的状态。

我必须重写这个组件吗?如果是,怎么做?或者我可以用更简单的方法吗?

在您的ConsoleListener中添加commandExecution属性

protected $commandExecution = null;

然后在你的onConsoleCommand()方法中设置

public function onConsoleCommand(ConsoleCommandEvent $event)
{
    $command = $event->getCommand();
    $commandEntity =     $this->em->getRepository('EvoCronBundle:Command')->findOneBy(['name' =>     $command->getName()]);
    $commandExecution = new CommandExecution();
    $commandExecution->setCommand($commandEntity);
    $this->em->persist($commandExecution);
    $this->em->flush();
    $this->commandExecution = $commandExecution;
}

然后您可以在onConsoleTerminate()方法中访问它

public function onConsoleTerminate(ConsoleTerminateEvent $event)
{
    $command = $event->getCommand();
    // here, retrieve the commandExecution entity passed in onConsoleCommand() method
    $commandExecution = $this->commandExecution;
    $commandExecution->setCompleted(true);
    $this->em->flush();
}

不要忘记测试onConsoleTerminate()方法中commandExecution的值是否为null

最新更新