As already mentioned, the class ezcConsoleOutput is the tool of choice for
printing text to the console. Let's look at a basic example:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->info->color = 'blue';
8.
9. $output->outputText( 'Test text in color blue', 'info' );
10.
11. ?>
The ezcConsoleOutput object is simply instantiated. You can optionally submit
options and predefined formating options to it's constructor, but this can also
be done later.
In line 7 you see how a format is defined. Formats are created on the fly, as
soon as you access them (for reading or writing) through the $output->formats
attribute. We create a format called "info" and assign the color value "blue"
to it in this case. This will make all text printed with this format occur in
blue. In line 9 you can see how the format is applied to a text while printing
it.
The second example shows some more advanced code:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->info->color = 'blue';
8.
9. $output->formats->error->color = 'red';
10. $output->formats->error->style = array( 'bold' );
11.
12. $output->formats->fatal->color = 'red';
13. $output->formats->fatal->style = array( 'bold', 'underlined' );
14. $output->formats->fatal->bgcolor = 'black';
15.
16. $output->outputText( 'This is some standard text ' );
17. $output->outputText( 'including some error', 'error' );
18. $output->outputText( ' wrapped in standard text.' );
19. $output->outputText( "\n" );
20.
21. $output->outputLine( 'This is a fatal error message.', 'fatal' );
22.
23. $output->outputText( 'Test' );
24.
25. ?>
In this example 2 more formats are defined: "error" and "fatal". These formats
have additional style attribute set, which makes them both appear bold. The
"fatal" format will additionally shown underlined text and will give it a
black background color.
The difference between ezcConsoleOutput::outputText() and
ezcConsoleOutput::outputLine() is, that the latter one automatically adds a
newline value to your text. The newline sequence used here is adjusted to
the operating system. The use of ezcConsoleOutput::outputLine() is recommended
over the direct output of e.g "n".
If you leave the second parameter of ezcConsoleOutput::outputText() and
ezcConsoleOutput::outputLine() out, the "default" format will use. Per default
this is set to your consoles default setting, but you can also change this as
for any other format you define. A third variant to format text is
ezcConsoleOutput::formatText(), which returns the formated string instead of
printing it.
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->info->color = 'blue';
8. $output->formats->info->style = array( 'bold' );
9.
10. $output->setOptions(
11. array(
12. 'autobreak' => 78,
13. 'verbosityLevel' => 3
14. )
15. );
16.
17. $output->outputLine( 'This is a very very long info text. It has so much information in '.
18. 'it, that it will definitly not fit into 1 line. Therefore, '.
19. 'ezcConsoleOutput will automatically wrap the line for us.', 'info' );
20.
21. $output->outputLine();
22.
23. $output->outputLine( 'This verbose information will currently not be displayed.', 'info', 10 );
24.
25. $output->outputLine( 'But this verbose information will be displayed.', 'info', 2 );
26.
27. ?>
This example shows some of the options ezcConsoleOutput supports:
- autobreak
- Will wrap lines automatically after the set amount of characters, keeping
word boundaries in tact.
- verbosityLevel
- Allows you to specify a 3rd parameter to ezcConsoleOutput::outputLine() and
ezcConsoleOutput::outputText() to indicate a verbosity level, when the text
should be printed. By setting the "verbosityLevel" option for ezcConsoleOutput
you define, which texts will be printed and which not.
In our example the call on line 23 would not print out text with the
"verbosityLevel" option set to 3, but the call on line 25 will.
A simple example for ezcConsoleInput:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $input = new ezcConsoleInput();
6.
7. $helpOption = $input->registerOption(
8. new ezcConsoleOption(
9. 'h',
10. 'help'
11. )
12. );
13.
14. try
15. {
16. $input->process();
17. }
18. catch ( ezcConsoleOptionException $e )
19. {
20. die( $e->getMessage() );
21. }
22.
23. if ( $helpOption->value !== false )
24. {
25. echo "Help requested.";
26. }
27. else
28. {
29. echo "No help requested.";
30. }
31.
32. ?>
After instantiating a new ezcConsoleInput object to handle the options, an
option is registered on lines 7-12. This option will be available as "-h" and
"--help". The ezcConsoleInput::process() call makes ezcConsoleInput work up the
options submitted by the user. If any error occurs with the submitted user
data, the method will throw an exception of type ezcConsoleOptionException. By
default all options are registered with the value type
ezcConsoleInput::TYPE_NONE, which indicates that they don't expect a value
form the user. If a value is submitted anyway, ezcConsoleInput::process() will
throw a ezcConsoleOptionTypeViolationException.
On line 23 a check if an option was submitted is performed. If an option was not
submitted, it's $value property will contain bool false. Depending on the $type
set, it can contain different value types if it was submitted. If you use the
(not shown here) ezcConsoleOption::$multiple property, the value will be an array
containing the specified value types.
The next example is more advanced:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $input = new ezcConsoleInput();
6.
7. $helpOption = $input->registerOption( new ezcConsoleOption( 'h', 'help' ) );
8.
9. $inputOption = $input->registerOption(
10. new ezcConsoleOption(
11. 'i',
12. 'input',
13. ezcConsoleInput::TYPE_STRING
14. )
15. );
16.
17. $outputOption = $input->registerOption(
18. new ezcConsoleOption(
19. 'o',
20. 'output'
21. )
22. );
23. $outputOption->type = ezcConsoleInput::TYPE_STRING;
24.
25. $inputOption->addDependency(
26. new ezcConsoleOptionRule( $outputOption )
27. );
28. $outputOption->addDependency(
29. new ezcConsoleOptionRule( $inputOption )
30. );
31.
32. try
33. {
34. $input->process();
35. }
36. catch ( ezcConsoleOptionException $e )
37. {
38. die( $e->getMessage() );
39. }
40.
41. if ( $helpOption->value === true )
42. {
43. echo $input->getSynopsis() . "\n";
44. foreach ( $input->getOptions() as $option )
45. {
46. echo "-{$option->short}/{$option->long}: {$option->shorthelp}\n";
47. }
48. }
49. elseif ( $outputOption->value !== false )
50. {
51. echo "Input: {$inputOption->value}, Output: {$outputOption->value}\n";
52. echo "Arguments: " . implode( ", ", $input->getArguments() ) . "\n";
53. }
54.
55. ?>
2 options are registered here: "-i"/"--input" and "-o"/"--output". For the
first one additional properties for the ezcConsoleOption object are submitted
through the constructor. For the second ezcConsoleOption object you see how to
provide additional properties after construction. We change the type of both
options to expect a string value from the user (lines 13 and 20).
In line 25 and 28 we make both parameters depend on each other. If one of them
is submitted without the other on, ezcConsoleInput::process() will throw an
ezcConsoleOptionDependencyViolationException. Beside dependency rules, you can
also define exclusion rules, using ezcConsoleOption::addExclusion().
On line 43 the method ezcConsoleInput::getSynopsis() is used to retrieve a
synopsis string for the program. The synopsis for our example would look like
this:
$ ./tutorial_example_05.php [-h] [-i <string> [-o <string>] ] [[--] <args>]
The synopsis will reflect the option value types, if they are optional, the
inter-option dependencies and default values (if set). On line 46 the property
ezcConsoleOption::$shorthelp is accessed, where you can store a short help
information. It has a reasonable default value set.
On line 49 the submission of the "-o" option is checked. Because this has a
dependency on the "-i" option, a check for this one is not necessary. Line 52
shows how you can access the arguments submitted to the program.
ezcConsoleInput::getArguments() always returns an array (empty if no arguments
are submitted).
Here is an example how the defined program would be called:
$ ./tutorial_example_05.php -i /var/www -o /tmp foo bar
For this input the program will print:
Input: /var/www, Output: /tmp
Arguments: foo, bar
For further information, please refer to the API documentation of
ezcConsoleInput.
This example defines a simple progressbar:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $bar = new ezcConsoleProgressbar( $output, 15 );
8.
9. for ( $i = 0; $i < 15; $i++ )
10. {
11. $bar->advance();
12. usleep( mt_rand( 2000, 200000 ) );
13. }
14.
15. $bar->finish();
16.
17. $output->outputLine();
18.
19. ?>
The created progressbar will count to a maximum value of 15, submitted to
ezcConsoleProgressbar::__construct() in line 7. ezcConsoleProgressbar utilizes
ezcConsoleOutput to print the generated progressbar. The call to
ezcConsoleProgressbar::advance() pushes the progressbar 1 step further on each
call and redraws it (line 11). Calling ezcConsoleProgressbar::finish() will set
the progressbar to 100% immediately.
The progressbar generated by the example will look like this:
The next example performs more customization on the progressbar appearance:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->bar->color = 'blue';
8. $output->formats->bar->style = array( 'bold' );
9.
10. $options = array(
11. 'emptyChar' => ' ',
12. 'barChar' => '-',
13. 'formatString' => '%fraction%% <' . $output->formatText( '%bar%', 'bar' ) . '> Uploaded %act% / %max% kb',
14. 'redrawFrequency' => 50,
15. );
16.
17. $bar = new ezcConsoleProgressbar( $output, 1024, $options );
18.
19. for ( $i = 0; $i < 1024; $i++ )
20. {
21. $bar->advance();
22. usleep( mt_rand( 200, 2000 ) );
23. }
24.
25. $bar->finish();
26.
27. $output->outputLine();
28.
29. ?>
The defined options array demonstrates only a small subset of options. For
detailed information look at ezcConsoleProgressbar::$options. The "emptyChar"
value defines the character to prefill the bar, the "barChar" option the
character to fill the bar with while calling ezcConsoleProgressbar::advance().
Using the "formatString" option, you defines the appearance of the whole bar.
Here the substitution of several place holders (like "%fraction%" and "%bar%")
is permitted. "The formatString" must contain the "%bar%" place holder, all
other values are optional. Any other printable character is permitted, too.
Beside that, formating options are allowed in the "formatString" option, but
not in any other option. "redrawFrequency" defines the how often the
progressbar will be redrawn. In the example this will be every 50th call to
ezcConsoleProgressbar::advance().
The resulting progressbar will look like this:
With the ezcConsoleStatusbar you can indicate progress of a time consuming action
in a simpler way. Here is an example:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->success->color = 'green';
8. $output->formats->failure->color = 'red';
9.
10. $options = array(
11. 'successChar' => $output->formatText( '+', 'success' ),
12. 'failureChar' => $output->formatText( '-', 'failure' ),
13. );
14.
15. $status = new ezcConsoleStatusbar( $output, $options );
16.
17. for ( $i = 0; $i < 120; $i++ )
18. {
19. $nextStatus = ( bool )mt_rand( 0,1 );
20. $status->add( $nextStatus );
21. usleep( mt_rand( 200, 2000 ) );
22. }
23.
24. $output->outputLine();
25. $output->outputLine( 'Successes: ' . $status->getSuccessCount() . ', Failures: ' . $status->getFailureCount() );
26.
27. ?>
This variant of indicating progress only displays success or failure indicators
for an action and allows you to run any number of actions, without specifying,
how many you will perform before. The "successChar" and "failureChar" options
indicate which string to print on a successful or failed action. Formatting
these strings is allowed here (lines 11 and 12).
Indicating a status is done using ezcConsoleStatusbar::add(), which expects
true for a succeeded action and false for a failed one (line 20). You can
access the number of successes and failures through
ezcConsoleStatusbar::getSuccessCount() and
ezcConsoleStatusbar::getFailureCount(). To make ezcConsoleStatusbar
wrap a line after a certain amount of statuses, you can use
ezcConsoleOutput::$autobreak.
Here the result of the example:
Finally the ezcConsoleProgressMonitor can indicate progress, but does not use a
bar-like interface. It simply prints status information about each action you
perform and shows the current progress as a percentage value in relation to the
number of actions you plan to perform overall.
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $status = new ezcConsoleProgressMonitor( $out, 7 );
8.
9. $i = 0;
10. while( $i++ < 7 )
11. {
12. usleep( mt_rand( 20000, 2000000 ) );
13. $status->addEntry( 'ACTION', "Performed action #{$i}." );
14. }
15.
16. $out->outputLine();
17.
18. ?>
Line 7 creates a new status-indicator, which will iterate over 7 actions.
Inside the while-loop the happening of some actions is simulated as usual. The
call to $status->addEntry() adds a status entry and causes the indicator to
print the entry. Every entry consists of a tag (first parameter) and a message.
The result of the example looks as follows:
14.3% ACTION Performed action #1.
28.6% ACTION Performed action #2.
42.9% ACTION Performed action #3.
57.1% ACTION Performed action #4.
71.4% ACTION Performed action #5.
85.7% ACTION Performed action #6.
100.0% ACTION Performed action #7.
More information on these classes can be taken from the API documentation of
ezcConsoleProgressbar, ezcConsoleStatusbar and ezcConsoleProgressMonitor.
This is the result of a table generated by ezcConsoleTable:
The source code for it is printed here:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $data = array(
6. array( 'Name', 'Nationality', 'Birthday' ),
7. array( 'Derick Rethans', 'Dutch', '1978-12-22' ),
8. array( 'Frederik Holljen', 'Canadian / Norwegian', '1978-11-15' ),
9. array( 'Jan Borsodi', 'Norwegian', '1977-10-13' ),
10. array( 'Raymond Bosman', 'Dutch', '1979-07-24' ),
11. array( 'Tobias Schlitt', 'German', '1980-05-19' ),
12. );
13.
14. $output = new ezcConsoleOutput();
15.
16. $output->formats->headBorder->color = 'blue';
17. $output->formats->normalBorder->color = 'gray';
18.
19. $output->formats->headContent->color = 'blue';
20. $output->formats->headContent->style = array( 'bold' );
21.
22. $table = new ezcConsoleTable( $output, 78 );
23.
24. $table->options->defaultBorderFormat = 'normalBorder';
25.
26. $table[0]->borderFormat = 'headBorder';
27. $table[0]->format = 'headContent';
28. $table[0]->align = ezcConsoleTable::ALIGN_CENTER;
29.
30. foreach ( $data as $row => $cells )
31. {
32. foreach ( $cells as $cell )
33. {
34. $table[$row][]->content = $cell;
35. }
36. }
37.
38. $output->outputLine( 'eZ components team:' );
39. $table->outputTable();
40. $output->outputLine();
41.
42.
43. ?>
ezcConsoleTable (like ezcConsoleStatusbar and ezcConsoleProgressbar) uses the
ezcConsoleOutput class to print to the console. To create a table you just
needs to submit the maximal width of the table to it's constructor:
ezcConsoleTable::__construct(). Options for the table formating are inherited
from the table itself, to the table rows and from there to the table cells.
On each inheritance level options might be overwritten individually. The
"defaultBorderFormat" option sets the global format value for all borders (line
24). This is overwritten in line 26 for the first row of the table.
Table rows are accessed as if you use an array in PHP (this is achieved by
implementing the ArrayAccess interface from SPL). Beside that,
ezcConsoleTable implements the Iterator interface (SPL, too) to allow
iteration over table rows using foreach. Each table row is represented by an
object of type ezcConsoleTableRow, which also implements the ArrayAccess and
Iterator interfaces to access cells contained in the rows in the same way. Each
of the named classes allows the access of it's properties as usual, beside access
to it's contained objects through the array interface.
ezcConsoleTableRow and ezcConsoleTableCell have a $format setting to define the
format of the contained text. All cells (as described above) will inherit the
setting of their parent ezcConsoleTableRow, as long as this has not been
explicitly overwritten. The same applies to ezcConsoleTableRow::$align and
ezcConsoleTableCell::$align. Possible align values are:
The content of a cell is stored in the ezcConsoleTableCell::$content property
(line 34). The usage of formated text in a cell is possible, but not recommended.
If you want to define the format of cell content, use the
ezcConsoleTableCell::$format property.
A more advanced (but in a way useless) example to show the handling of tables
a bit more:
1. <?php
2.
3. require_once 'tutorial_autoload.php';
4.
5. $output = new ezcConsoleOutput();
6.
7. $output->formats->blue->color = 'blue';
8. $output->formats->blue->style = array( 'bold' );
9. $output->formats->red->color = 'red';
10. $output->formats->red->style = array( 'bold' );
11. $output->formats->green->color = 'green';
12. $output->formats->green->style = array( 'bold' );
13.
14. $colors = array( 'red', 'blue', 'green' );
15. $aligns = array( ezcConsoleTable::ALIGN_LEFT, ezcConsoleTable::ALIGN_CENTER, ezcConsoleTable::ALIGN_RIGHT );
16.
17. $table = new ezcConsoleTable( $output, 78 );
18.
19. $table->options->corner = ' ';
20. $table->options->lineHorizontal = ' ';
21. $table->options->lineVertical = ' ';
22. $table->options->widthType = ezcConsoleTable::WIDTH_FIXED;
23.
24. for ( $i = 0; $i < 10; $i++ )
25. {
26. for ( $j = 0; $j < 10; $j++ )
27. {
28. $table[$i][$j]->content = '*';
29. $table[$i][$j]->format = $colors[array_rand( $colors )];
30. $table[$i][$j]->align = $aligns[array_rand( $aligns )];
31. }
32. }
33.
34. $table->outputTable();
35. $output->outputLine();
36.
37.
38. ?>
The "corner", "lineHorizontal" and "lineVertical" options define, which
characters to use to define the borders of the table. These options must be
exactly 1 character long and my not contain formating information. To style the
borders, use the ezcConsoleTable::$defaultBorderFormat and
ezcConsoleTableRow::$borderFormat properties.
The random format and alignment options selected above create the following
table: