我有一个运行辅助类的控制台命令,我想用$this->info()
将输出写入辅助类的控制台。
我的代码看起来像这样:
App/Http/Console/Commands/SomeCommand.php
function handle(Helper $helper)
{
return $helper->somefunction();
}
App/Http/SomeHelper.php
function somefunction()
{
//some code
$this->info('send to console');
}
有没有办法从助手写输出到控制台?
在SomeCommand类的handle()
函数中,添加$this->myHelper->setConsoleOutput($this->getOutput());
。
在你的助手类中,添加:
/**
*
* @var \Symfony\Component\Console\Style\OutputStyle
*/
protected $consoleOutput;
/**
*
* @param \Symfony\Component\Console\Style\OutputStyle $consoleOutput
* @return $this
*/
public function setConsoleOutput($consoleOutput) {
$this->consoleOutput = $consoleOutput;
return $this;
}
/**
*
* @param string $text
* @return $this
*/
public function writeToOuput($text) {
if ($this->consoleOutput) {
$this->consoleOutput->writeln($text);
}
return $this;
}
/**
*
* @param string $text
* @return $this
*/
public function writeErrorToOuput($text) {
if ($this->consoleOutput) {
$style = new \Symfony\Component\Console\Formatter\OutputFormatterStyle('white', 'red', ['bold']); //white text on red background
$this->consoleOutput->getFormatter()->setStyle('error', $style);
$this->consoleOutput->writeln('<error>' . $text . '</error>');
}
return $this;
}
然后,在您的助手类中的任何其他位置,您可以使用:
$this->writeToOuput('Here is a string that I want to show in the console.');
您需要在SomeCommand.php文件中编写$this->info('send to console');
。对于写入输出,请按照此https://laravel.com/docs/5.2/artisan#writing-output
我没试过,但也许:$this->line("sent to console');