How to Style a Console Command

How to Style a Console Command

One of the most boring tasks when creating console commands is to deal with the styling of the command’s input and output. Displaying titles and tables or asking questions to the user involves a lot of repetitive code.

Consider for example the code used to display the title of the following command:

  1. // src/Command/GreetCommand.php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. class GreetCommand extends Command
  7. {
  8. // ...
  9. protected function execute(InputInterface $input, OutputInterface $output): int
  10. {
  11. $output->writeln([
  12. '<info>Lorem Ipsum Dolor Sit Amet</>',
  13. '<info>==========================</>',
  14. '',
  15. ]);
  16. // ...
  17. }
  18. }

Displaying a simple title requires three lines of code, to change the font color, underline the contents and leave an additional blank line after the title. Dealing with styles is required for well-designed commands, but it complicates their code unnecessarily.

In order to reduce that boilerplate code, Symfony commands can optionally use the Symfony Style Guide. These styles are implemented as a set of helper methods which allow to create semantic commands and forget about their styling.

Basic Usage

In your command, instantiate the Symfony\Component\Console\Style\SymfonyStyle class and pass the $input and $output variables as its arguments. Then, you can start using any of its helpers, such as title(), which displays the title of the command:

  1. // src/Command/GreetCommand.php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use Symfony\Component\Console\Style\SymfonyStyle;
  7. class GreetCommand extends Command
  8. {
  9. // ...
  10. protected function execute(InputInterface $input, OutputInterface $output): int
  11. {
  12. $io = new SymfonyStyle($input, $output);
  13. $io->title('Lorem Ipsum Dolor Sit Amet');
  14. // ...
  15. }
  16. }

Helper Methods

The Symfony\Component\Console\Style\SymfonyStyle class defines some helper methods that cover the most common interactions performed by console commands.

Titling Methods

[title()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::title()")

It displays the given string as the command title. This method is meant to be used only once in a given command, but nothing prevents you to use it repeatedly:

  1. $io->title('Lorem ipsum dolor sit amet');

[section()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::section()")

It displays the given string as the title of some command section. This is only needed in complex commands which want to better separate their contents:

  1. $io->section('Adding a User');
  2. // ...
  3. $io->section('Generating the Password');
  4. // ...

Content Methods

[text()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::text()")

It displays the given string or array of strings as regular text. This is useful to render help messages and instructions for the user running the command:

  1. // use simple strings for short messages
  2. $io->text('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long messages
  5. $io->text([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. 'Aenean sit amet arcu vitae sem faucibus porta',
  9. ]);

[listing()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::listing()")

It displays an unordered list of elements passed as an array:

  1. $io->listing([
  2. 'Element #1 Lorem ipsum dolor sit amet',
  3. 'Element #2 Lorem ipsum dolor sit amet',
  4. 'Element #3 Lorem ipsum dolor sit amet',
  5. ]);

[table()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::table()")

It displays the given array of headers and rows as a compact table:

  1. $io->table(
  2. ['Header 1', 'Header 2'],
  3. [
  4. ['Cell 1-1', 'Cell 1-2'],
  5. ['Cell 2-1', 'Cell 2-2'],
  6. ['Cell 3-1', 'Cell 3-2'],
  7. ]
  8. );

[horizontalTable()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::horizontalTable()")

It displays the given array of headers and rows as a compact horizontal table:

  1. $io->horizontalTable(
  2. ['Header 1', 'Header 2'],
  3. [
  4. ['Cell 1-1', 'Cell 1-2'],
  5. ['Cell 2-1', 'Cell 2-2'],
  6. ['Cell 3-1', 'Cell 3-2'],
  7. ]
  8. );

New in version 4.4: The horizontalTable() method was introduced in Symfony 4.4.

[definitionList()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::definitionList()")

It displays the given key => value pairs as a compact list of elements:

  1. $io->definitionList(
  2. 'This is a title',
  3. ['foo1' => 'bar1'],
  4. ['foo2' => 'bar2'],
  5. ['foo3' => 'bar3'],
  6. new TableSeparator(),
  7. 'This is another title',
  8. ['foo4' => 'bar4']
  9. );

New in version 4.4: The definitionList() method was introduced in Symfony 4.4.

[newLine()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::newLine()")

It displays a blank line in the command output. Although it may seem useful, most of the times you won’t need it at all. The reason is that every helper already adds their own blank lines, so you don’t have to care about the vertical spacing:

  1. // outputs a single blank line
  2. $io->newLine();
  3. // outputs three consecutive blank lines
  4. $io->newLine(3);

Admonition Methods

[note()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::note()")

It displays the given string or array of strings as a highlighted admonition. Use this helper sparingly to avoid cluttering command’s output:

  1. // use simple strings for short notes
  2. $io->note('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long notes
  5. $io->note([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. 'Aenean sit amet arcu vitae sem faucibus porta',
  9. ]);

[caution()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::caution()")

Similar to the note() helper, but the contents are more prominently highlighted. The resulting contents resemble an error message, so you should avoid using this helper unless strictly necessary:

  1. // use simple strings for short caution message
  2. $io->caution('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long caution messages
  5. $io->caution([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. 'Aenean sit amet arcu vitae sem faucibus porta',
  9. ]);

Progress Bar Methods

[progressStart()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::progressStart()")

It displays a progress bar with a number of steps equal to the argument passed to the method (don’t pass any value if the length of the progress bar is unknown):

  1. // displays a progress bar of unknown length
  2. $io->progressStart();
  3. // displays a 100-step length progress bar
  4. $io->progressStart(100);

[progressAdvance()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::progressAdvance()")

It makes the progress bar advance the given number of steps (or 1 step if no argument is passed):

  1. // advances the progress bar 1 step
  2. $io->progressAdvance();
  3. // advances the progress bar 10 steps
  4. $io->progressAdvance(10);

[progressFinish()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::progressFinish()")

It finishes the progress bar (filling up all the remaining steps when its length is known):

  1. $io->progressFinish();

User Input Methods

[ask()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::ask()")

It asks the user to provide some value:

  1. $io->ask('What is your name?');

You can pass the default value as the second argument so the user can hit the <Enter> key to select that value:

  1. $io->ask('Where are you from?', 'United States');

In case you need to validate the given value, pass a callback validator as the third argument:

  1. $io->ask('Number of workers to start', 1, function ($number) {
  2. if (!is_numeric($number)) {
  3. throw new \RuntimeException('You must type a number.');
  4. }
  5. return (int) $number;
  6. });

[askHidden()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::askHidden()")

It’s very similar to the ask() method but the user’s input will be hidden and it cannot define a default value. Use it when asking for sensitive information:

  1. $io->askHidden('What is your password?');

In case you need to validate the given value, pass a callback validator as the second argument:

  1. $io->askHidden('What is your password?', function ($password) {
  2. if (empty($password)) {
  3. throw new \RuntimeException('Password cannot be empty.');
  4. }
  5. return $password;
  6. });

[confirm()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::confirm()")

It asks a Yes/No question to the user and it only returns true or false:

  1. $io->confirm('Restart the web server?');

You can pass the default value as the second argument so the user can hit the <Enter> key to select that value:

  1. $io->confirm('Restart the web server?', true);

[choice()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::choice()")

It asks a question whose answer is constrained to the given list of valid answers:

  1. $io->choice('Select the queue to analyze', ['queue1', 'queue2', 'queue3']);

You can pass the default value as the third argument so the user can hit the <Enter> key to select that value:

  1. $io->choice('Select the queue to analyze', ['queue1', 'queue2', 'queue3'], 'queue1');

Result Methods

[success()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::success()")

It displays the given string or array of strings highlighted as a successful message (with a green background and the [OK] label). It’s meant to be used once to display the final result of executing the given command, but you can use it repeatedly during the execution of the command:

  1. // use simple strings for short success messages
  2. $io->success('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long success messages
  5. $io->success([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. ]);

[warning()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::warning()")

It displays the given string or array of strings highlighted as a warning message (with a red background and the [WARNING] label). It’s meant to be used once to display the final result of executing the given command, but you can use it repeatedly during the execution of the command:

  1. // use simple strings for short warning messages
  2. $io->warning('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long warning messages
  5. $io->warning([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. ]);

[error()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::error()")

It displays the given string or array of strings highlighted as an error message (with a red background and the [ERROR] label). It’s meant to be used once to display the final result of executing the given command, but you can use it repeatedly during the execution of the command:

  1. // use simple strings for short error messages
  2. $io->error('Lorem ipsum dolor sit amet');
  3. // ...
  4. // consider using arrays when displaying long error messages
  5. $io->error([
  6. 'Lorem ipsum dolor sit amet',
  7. 'Consectetur adipiscing elit',
  8. ]);

Defining your Own Styles

If you don’t like the design of the commands that use the Symfony Style, you can define your own set of console styles. Create a class that implements the Symfony\Component\Console\Style\StyleInterface:

  1. namespace App\Console;
  2. use Symfony\Component\Console\Style\StyleInterface;
  3. class CustomStyle implements StyleInterface
  4. {
  5. // ...implement the methods of the interface
  6. }

Then, instantiate this custom class instead of the default SymfonyStyle in your commands. Thanks to the StyleInterface you won’t need to change the code of your commands to change their appearance:

  1. // src/Command/GreetCommand.php
  2. namespace App\Console;
  3. use App\Console\CustomStyle;
  4. use Symfony\Component\Console\Command\Command;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. class GreetCommand extends Command
  8. {
  9. // ...
  10. protected function execute(InputInterface $input, OutputInterface $output): int
  11. {
  12. // Before
  13. $io = new SymfonyStyle($input, $output);
  14. // After
  15. $io = new CustomStyle($input, $output);
  16. // ...
  17. }
  18. }

Writing to the error output

If you reuse the output of a command as the input of other commands or dump it into a file for later reuse, you probably want to exclude progress bars, notes and other output that provides no real value.

Commands can output information in two different streams: stdout (standard output) is the stream where the real contents should be output and stderr (standard error) is the stream where the errors and the debugging messages should be output.

The Symfony\Component\Console\Style\SymfonyStyle class provides a convenient method called [getErrorStyle()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Console/Style/SymfonyStyle.php "Symfony\Component\Console\Style\SymfonyStyle::getErrorStyle()") to switch between both streams. This method returns a new SymfonyStyle instance which makes use of the error output:

  1. $io = new SymfonyStyle($input, $output);
  2. // Write to the standard output
  3. $io->write('Reusable information');
  4. // Write to the error output
  5. $io->getErrorStyle()->warning('Debugging information or errors');

Note

If you create a SymfonyStyle instance with an OutputInterface object that is not an instance of Symfony\Component\Console\Output\ConsoleOutputInterface, the getErrorStyle() method will have no effect and the returned object will still write to the standard output instead of the error output.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.