没有 OutputInterface 的 Symfony2 控制台输出

2024-05-05

我正在尝试使用 Symfony 控制台命令将一些信息打印到控制台。通常你会做这样的事情:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $name = $input->getArgument('name');
    if ($name) {
        $text = 'Hello '.$name;
    } else {
        $text = 'Hello';
    }

    if ($input->getOption('yell')) {
        $text = strtoupper($text);
    }

    $output->writeln($text);
}

示例的完整代码 - Symfony 文档 http://symfony.com/doc/current/components/console/introduction.html#creating-a-basic-command

不幸的是我无法访问OutputInterface。是否可以将消息打印到控制台?

不幸的是我无法通过OutputInterface到我想打印一些输出的类。


了解准时调试的问题后,您始终可以使用以下命令打印调试消息echo or var_dump

如果您打算在没有 Symfony 应用程序的情况下使用带有全局调试消息的命令,可以使用以下方法。

Symfony 提供 3 种不同的OutputInterfaces

  • 空输出 http://api.symfony.com/2.3/Symfony/Component/Console/Output/NullOutput.html- 将导致根本没有输出并保持命令安静
  • 控制台输出 http://api.symfony.com/2.3/Symfony/Component/Console/Output/ConsoleOutput.html- 将导致控制台消息
  • 流输出 http://api.symfony.com/2.3/Symfony/Component/Console/Output/StreamOutput.html- 将导致将消息打印到给定的流中

调试到文件

这样做,每当你打电话时$output->writeln()在你的命令中,它将写入一个新行/path/to/debug/file.log

use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$file   = '/path/to/debug/file.log';
$handle = fopen($file, 'w+');
$output = new StreamOutput($handle);

$command = new MyCommand;
$command->run($input, $output);

fclose($handle);

在控制台中调试

这是相同的过程,只是您使用ConsoleOutput instead

use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$output = new ConsoleOutput();

$command = new MyCommand;
$command->run($input, $output);

无需调试

不会打印任何消息

use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$output = new NullOutput();

$command = new MyCommand;
$command->run($input, $output);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有 OutputInterface 的 Symfony2 控制台输出 的相关文章

随机推荐