Write output to console from helper class

2019-07-19 13:22发布

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.

My code looks like this:

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?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-19 13:57

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

查看更多
淡お忘
3楼-- · 2019-07-19 14:01

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.');
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-19 14:17

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

查看更多
登录 后发表回答