我有一个Symfony2控制台应用程序,其中包含一些命令:
$application = new Application();
$application->add(new MyCommand1());
$application->add(new MyCommand2());
$application->run();
运行应用程序时,我希望将输出重定向到控制台和到文件。
我可以使用StreamOutput,但如果我手动运行其中一个命令,我看起来只能提供这样的输出对象:
$input = ...;
$output = new StreamOutput(fopen('output.log', 'a'));
$command = new MyCommand1();
$command->run($input, $output);
但这不是我想要的。
是否可以向Application
本身添加辅助输出?以便所有命令都输出到控制台和文件。
答案 0 :(得分:3)
要完成这项任务,我会创建自己的输出。
class MultipleOutput implements OutputInterface
{
protected $outputs = array();
public function __construct(array $outputs = array())
{
$this->setOutputs($outputs);
}
public function setOutputs(array $outputs = array())
{
foreach ($outputs as $output) {
$this->addOutput($outputs);
}
}
public function addOutput(OutputInterface $output)
{
$this->outputs[] = $output;
}
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
foreach ($this->outputs as $output) {
$output->write($messages, $newline, $type);
}
}
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
foreach ($this->outputs as $output) {
$output->writeln($messages, $type);
}
}
public function setVerbosity($level)
{
foreach ($this->outputs as $output) {
$output->setVerbosity($level);
}
}
/**
* Returns only the first one
*/
public function getVerbosity()
{
foreach ($this->outputs as $output) {
return $output->getVerbosity();
}
}
public function setDecorated($decorated)
{
foreach ($this->outputs as $output) {
$output->setDecorated($decorated);
}
}
/**
* Returns only the first one
*/
public function isDecorated()
{
foreach ($this->outputs as $output) {
return $output->isDecorated();
}
}
public function setFormatter(OutputFormatterInterface $formatter)
{
foreach ($this->outputs as $output) {
$output->setFormatter($formatter);
}
}
/**
* Returns only the first one
*/
public function getFormatter()
{
foreach ($this->outputs as $output) {
return $output->getFormatter();
}
}
}
然后您可以在您的应用程序中使用它
$application = new Application();
$application->add(new MyCommand1());
$application->add(new MyCommand2());
$output = new MultipleOutput(array(new StreamOutput, new ConsoleOutput));
$application->run(new ArgvInput, $output);