In Laravel 5 I enjoy its nice console output based on Symfony Console Component. Working with legacy code in Yii in console we have a very poor output. We can use echo and format the output ourselves. The better choice is to integrate Symfony component in Yii and use it for formatted output.
First of all, we need to install it via composer:
Then we need to add Composer’s autoload.php file to Yii console entry point file yiic.php:
Extend ConsoleCommand class
Next, we can extend Yii CConsoleCommand class and create our own console command class with some helper methods:
To use Symfony formatted output we need to have an instance of the OutputInterface. The better place to instantiate it is Yii components init() method:
There are several implementations of the OutputInterface. We will use ConsoleOutput one. Next step is to add some helper methods for formatted output: error, info, line and comment. Behind the scenes they will delegate to OutputInterface::writeln() methods with different tags:
Now in our console command we can inherit from the new EConsoleCommand and use its methods:
Progress bar is very useful working with long-running commands. You can see the current pretty formatted progress of your command. Let’s add this functionality to our commands. ProgressBar is already available in Symonfy Console Component. Its constructor requires an instance of the OutputInterface, which we already have in our base command class:
Then, in our StatisticsCommand, we can output the current progress of the command. There are three common methods in ProgressBar class for progress output: start(), finish() and advance():
Symfony Console Component is a very powerful tool. There are many advanced formatted output options: questions, tables and other. Also, we can configure a progress bar as we want. For more details take a look at Symfony Console Component docs and ProgressBar docs.
@ 2018. All rights reserved.
If you've got any feedback, comments or just want to chat you can get in
touch via Twitter or email.