3

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?

1
  • Maybe if you extend Illuminate\Console\Command. Commented Jun 6, 2016 at 13:40

3 Answers 3

4

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.');
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I know it works there, but I need to output from the helper too.
@Alex try create a instance of SomeCommand and and then use that object instead of $this
-3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.