Write output to console from helper class

岁酱吖の 提交于 2019-12-05 19:24:13

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.');

You need to write $this->info('send to console'); this in SomeCommand.php file.For writing output follow this https://laravel.com/docs/5.2/artisan#writing-output

I have not tried, but maybe: $this->line("sent to console');

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!