支付宝扫一扫付款
                    微信扫一扫付款
(微信为保护隐私,不显示你的昵称)
DebugFormatterHelper 提供的方法,可以在运行一个外部程序,例如一个进程或一个HTTP请求的时候,输出调试信息。举例来说,如果你使用它在UNIX系统上来输出 ls -la 的运行结果,它可能输出以下内容:

formatter已被包含在默认的助手集中,你可以调用 getHelper()来获取它:
1  | $debugFormatter = $this->getHelper('debug_formatter'); | 
formatter接收字符串,返回格式化的字符串,以便你在命令行中输出(甚至可以记录下相关信息,或做其他一些事)。
本助手的所有方法,都有一个识别符,作为第一个参数。在每个程序中,这是个唯一值。在这种方式下,helper可以在同一时间对多套程序获取调试信息。当使用 Process组件 时,你可能希望使用 spl_object_hash。
默认时这种信息往往特别冗长。你可以使用 verbosity levels 仅在debug模式下才显示 (-vvv)。
只要程序一启动,你就可以使用 start() 来显示该程序的信息:
1 2 3 4 5 6 7 8 9  | // ...
$process = new Process(...);
 
$output->writeln($debugFormatter->start(
    spl_object_hash($process),
    'Some process description'
));
 
$process->run(); | 
这将输出:
1  | RUN Some process description | 
你可以使用第三个参数调整前缀:
1 2 3 4 5 6 7  | $output->writeln($debugFormatter->start(
    spl_object_hash($process),
    'Some process description',
    'STARTED'
));
// will output:
//  STARTED Some process description | 
有些程序在运行时会进行输出,使用 progress() 可以显示这个信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  | use Symfony\Component\Process\Process;
 
// ...
$process = new Process(...);
 
$process->run(function ($type, $buffer) use ($output, $debugFormatter, $process) {
    $output->writeln(
        $debugFormatter->progress(
            spl_object_hash($process),
            $buffer,
            Process::ERR === $type
        )
    );
});
// ... | 
如果成功,这将输出:
1  | OUT The output of the process | 
失败的话会是这样:
1  | ERR The output of the process | 
第三个参数是boolean,用于告诉函数这个output“是否是错的”。如果设为 true,则output会被认为是错误的输出。
第四和第五个参数分别允许你覆写normal output以及error output的前缀。
当程序中止时,你可以使用 stop() 来通知当前用户:
1 2 3 4 5 6 7 8  | // ...
$output->writeln(
    $debugFormatter->stop(
        spl_object_hash($process),
        'Some command description',
        $process->isSuccessful()
    )
); | 
这将输出:
1  | RES Some command description | 
失败的话,将以红色显示,而成功则是绿色。
如前面提到过的,你可以使用本助手在同一时间显示多个程序。不同程序的信息会以不同颜色来表示,以令“输出属于哪个命令”更加清晰。
本文,包括例程代码在内,采用的是 Creative Commons BY-SA 3.0 创作共用授权。