Php 如何在Symfony2控制台应用程序中添加辅助输出?
我有一个Symfony2控制台应用程序,其中包含一些命令:Php 如何在Symfony2控制台应用程序中添加辅助输出?,php,symfony,Php,Symfony,我有一个Symfony2控制台应用程序,其中包含一些命令: $application=新应用程序(); $application->add(新建MyCommand1()); $application->add(新建MyCommand2()); $application->run(); 运行应用程序时,我希望将输出重定向到控制台和文件 我可以使用它,但如果我手动运行以下命令之一,我似乎只能提供这样的输出对象: $input=。。。; $output=newstreamoutput(fopen('
$application=新应用程序();
$application->add(新建MyCommand1());
$application->add(新建MyCommand2());
$application->run();
运行应用程序时,我希望将输出重定向到控制台和文件
我可以使用它,但如果我手动运行以下命令之一,我似乎只能提供这样的输出对象:
$input=。。。;
$output=newstreamoutput(fopen('output.log','a');
$command=new MyCommand1();
$command->run($input,$output);
但这不是我想要的
是否可以将辅助输出添加到
应用程序本身?
以便所有命令同时输出到控制台和文件。要完成此任务,我将创建自己的输出
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);
您可以使用monolog来实现这一点。谢谢,我忽略了一个事实,即您实际上可以将输出传递给
Application::run()
!这个MultipleOutput
在Symfony中可能很有用。顺便问一下,pull请求怎么样?@Benjamin我迟早会试试的!