Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Console Output without OutputInterface

Tags:

symfony

I am trying to print some Information to the Console in a Symfony Console Command. Regularly you would do something like this:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $name = $input->getArgument('name');
    if ($name) {
        $text = 'Hello '.$name;
    } else {
        $text = 'Hello';
    }

    if ($input->getOption('yell')) {
        $text = strtoupper($text);
    }

    $output->writeln($text);
}

For the full Code of the Example - Symfony Documentation

Unfortunately I can't access the OutputInterface. Is it possible to print a Message to the Console?

Unfortunately I can't pass the OutputInterface to the Class where I want to print some Output.

like image 440
Robin Avatar asked Aug 14 '13 16:08

Robin


1 Answers

Understanding the matter of ponctual debugging, you can always print debug messages with echo or var_dump

If you plan to use a command without Symfony's application with global debug messages, here's a way to do this.

Symfony offers 3 different OutputInterfaces

  • NullOutput - Will result in no output at all and keep the command quiet
  • ConsoleOutput - Will result in console messages
  • StreamOutput - Will result in printing messages into a given stream

Debugging to a file

Doing such, whenever you call $output->writeln() in your command, it will write a new line in /path/to/debug/file.log

use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$file   = '/path/to/debug/file.log';
$handle = fopen($file, 'w+');
$output = new StreamOutput($handle);

$command = new MyCommand;
$command->run($input, $output);

fclose($handle);

Debugging in the console

It is quietly the same process, except that you use ConsoleOutput instead

use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$output = new ConsoleOutput();

$command = new MyCommand;
$command->run($input, $output);

No debugging

No message will be printed

use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Acme\FooBundle\Command\MyCommand;

$params = array();
$input  = new ArrayInput($params);

$output = new NullOutput();

$command = new MyCommand;
$command->run($input, $output);
like image 62
Touki Avatar answered Nov 15 '22 07:11

Touki