覆盖Symfony \ Component \ Console \ Commande \ Command.php

时间:2015-05-19 15:43:54

标签: symfony console command override

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

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

我正在使用console events来创建和保留此实体。

我的服务:

kernel.listener.console:
        class: Evo\CronBundle\EventListener\ConsoleListener
        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();
}

正如您在这些方法中所看到的,我想将一个commandExecution属性添加到Symfony Component Console \ Command \ Command.php中,这样我就可以传入commandExecution实体并更改其状态。

我是否必须覆盖此组件?如果有,怎么样?或者我可以用更简单的方式做到这一点吗?

1 个答案:

答案 0 :(得分:1)

commandExecution

中添加ConsoleListener媒体资源
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();
}

请勿忘记在commandExecution方法中测试onConsoleTerminate()值是否为空