php - 服务的 Symfony 命令行程序输出

标签 php symfony

我有一个 Symfony 服务,它处理一个文件并用它的信息做一些事情。我从 Controller 中调用此服务,并与命令类分开。实际服务需要很长时间才能运行,我想在处理文件时在命令行上显示一些状态输出。如果不在我的服务中添加 echo 命令,最好的方法是什么?

编辑 这似乎是解决方案:http://symfony.com/blog/new-in-symfony-2-4-show-logs-in-console

最佳答案

有这样的命令

$output->write('Blah blah blah');

$output->writeLn('Blah blah blah'); // Above with a line break

您还可以添加颜色和进度条以及可能的其他我从未使用过的内容。 http://symfony.com/doc/current/components/console/introduction.html#coloring-the-output

更新

您可以使用 EventDisptcher 服务来更新服务中事件的命令。 例如……

你指挥

protected function execute(InputInterface $input, OutputInterface $output)
{
    //....

    $dispatcher = $this->getContainer->get('event_dispatcher');

    $dispatcher->addListener(
        'an.event.that.you.have.set.up', 
        function (GenericEvent $event) use ($output) {
            $output->writeLn('<info>This event has happened</info');
        }
    });

    //....
}

您的服务

protected $dispatcher;

//....

public function __construct(EventDispatcherInterface $dispatcher, ...)
{
    $this->dispatcher = $dispatcher;
    //...
}

public function someFunction()
{
    //...

    $variable = 'something you are using');

    $dispatcher->dispatch(
        'an.event.that.you.have.set.up', 
        new GenericEvent($variable)
    );

    //...
}

显然,您可以指挥您的服务,但这里提供了如何将它们联系在一起的基础知识。

可以在这里看到一个实际的使用示例..

命令 - https://github.com/Richtermeister/Sylius/blob/subscription-bundle/src/Sylius/Bundle/SubscriptionBundle/Command/ProcessSubscriptionsCommand.php

服务 - https://github.com/Richtermeister/Sylius/blob/subscription-bundle/src/Sylius/Bundle/SubscriptionBundle/Processor/SubscriptionProcessor.php

关于php - 服务的 Symfony 命令行程序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003782/

相关文章:

php - 缺少必需表单字段的 Symfony 验证错误消息

javascript - 在php中以编程方式生成数组名称

javascript - 将参数从 twig 传递到 Angular

php - 在 Symfony 2.8、3.0 及更高版本中将数据传递给 buildForm()

PHP 函数到 Javascript : scan string and add words in array

symfony - PhpStorm 无法识别 Doctrine 实体类

twitter-bootstrap-3 - 遵循 Bootstrap 3 表单的手动说明获取 yml 配置错误

php - 如何将 example.com/index.php#anchor 的 URL 重写为 example.com/anchor?

php - Linux 上的 xampp phpmyadmin 访问被拒绝错误(#2002)

PHP/MySQL where 子句返回空值