本文介绍了将输出从助手类写入控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个运行帮助程序类的控制台命令,我想用$this->info()
的输出内容从帮助程序类写入控制台.
I have a console command that runs a helper class and I want to write output with $this->info()
to the console from the helper class.
我的代码如下:
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');
}
有什么方法可以将帮助程序的输出写入控制台?
Is there any way to write the output to console from the helper?
推荐答案
我终于弄清楚了(在Laravel 5.6中工作)
在 SomeCommand 类的handle()
函数中,添加$this->myHelper->setConsoleOutput($this->getOutput());
.
I finally figured this out (works in Laravel 5.6)
In the handle()
function of your SomeCommand class, add $this->myHelper->setConsoleOutput($this->getOutput());
.
在您的帮助程序类中,添加:
In your helper class, add:
/**
*
* @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;
}
然后,在您的帮助程序类中的其他任何地方,您都可以使用:
Then, anywhere else in your helper class, you can use:
$this->writeToOuput('Here is a string that I want to show in the console.');
这篇关于将输出从助手类写入控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!