为了账号安全,请及时绑定邮箱和手机立即绑定

从 Symfony 5 OutputInterface 获取整个控制台输出

从 Symfony 5 OutputInterface 获取整个控制台输出

PHP
潇潇雨雨 2022-12-03 11:05:24
我有一个像这样的 Symfony 5 命令:use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Output\OutputInterface;use Symfony\Component\Console\Style\SymfonyStyle;....    protected function execute(InputInterface $input, OutputInterface $output): int    {        $this->input        = $input;        $this->output       = $output;        $this->io           = new SymfonyStyle($input, $output);        ....    }此命令生成大量带有$this->io->caution(...)、$this->io->block(....)等 的输出$this->io->text(....)。有时(不总是:有一些运行时条件),在执行结束时,我想访问命令生成的整个输出,然后通过电子邮件发送。那么....我怎样才能取回OutputInterface显示的所有内容?有$this->output->getBuffer()什么吗?我可以毫无问题地交换OutputInterface $output其他东西(logger,也许?),只要我仍然可以像我现在所做的那样在 stdoutput (我的终端)上显示所有内容。
查看完整描述

1 回答

?
弑天下

TA贡献1818条经验 获得超7个赞

我认为没有现成的东西可以为您完成此任务。你可以用记录器实现类似的东西......但是你必须摆弄配置错误级别,可能注入多个记录器,控制台输出永远不会匹配一个SymfonyStyle,等等。


您最好自己构建,这应该不是特别困难。只需构建一些包装/装饰的东西SymfonyStyle;并捕获输出。


我将提供起始构建块,由您来完成实施:


class LoggingStyle

{

    private SymfonyStyle $style;

    private array        $logEntries = [];


    public function __construct(InputInterface $input, OutputInterface $output) {

        $this->style = new SymfonyStyle($input, $output);

    }


    private function addLog(string $type, string $message): void

    {

        $this->logEntries[] = [

            'type' => $type,

            'message' => $message,

            'time' => date('Y-m-d H:i:s')

        ];

    }


    public function flushLog():array

    {

        $log = $this->logEntries;

        $this->logEntries = [];


        return $log;

    }


    public function caution(string $message): void

    {

        $this->addLog('caution', $message);

        $this->style->caution($message);

    }


    public function text(string $message): void

    {

        $this->addLog('text', $message);

        $this->style->caution($message);

    }


    public function block(string $message): void

    {

        $this->addLog('block', $message);

        $this->style->caution($message);

    }

}


您需要实现SymfonyStyle您需要使用的界面的每个部分,并决定如何处理某些特殊行为(如果有的话)(例如,诸如 、 或进度条之类的东西ask())table()。但这完全取决于您的实施。


还要决定如何格式化电子邮件中的每种不同输出样式,因为逻辑上没有办法直接翻译它。


您可以直接使用此类,如果达到需要聚合输出的程度,您只需调用LoggingStyle::flushLog()并获取数组形式的所有条目,以便您进行相应处理和发送。


查看完整回答
反对 回复 2022-12-03
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信