Application Console¶
This section provides an introduction into console service. Console tools are ideal for use in cron jobs, or command line based utilities that don’t need to be accessible from a web browser.
- Powered by CLImate
Console Commands¶
Console command is a class defining a route and an event handler.
use WebinoAppLib\Console\AbstractConsoleCommand;
use WebinoAppLib\Event\ConsoleEvent;
use WebinoConfigLib\Feature\Route\ConsoleRoute;
class MyConsoleCommand extends AbstractConsoleCommand
{
public function configure(ConsoleRoute $route)
{
$route
->setPath('my-command')
->setTitle('My command title')
->setDescription('My command description.');
}
public function handle(ConsoleEvent $event)
{
// obtaining console service
$cli = $event->getCli();
// obtaining command parameters
$event->getParam('myCommandArgument');
// doing something...
$cli->out('My console command example!');
}
}
Adding custom console command into application configuration.
Webino::config([
new MyConsoleCommand,
]);
Console Bind¶
It is also possible to configure console command routes particularly.
use WebinoConfigLib\Feature\Route\ConsoleRoute;
Webino::config([
(new ConsoleRoute('my-command'))
->setPath('my-command')
->setTitle('My command title')
->setDescription('My command description.'),
]);
You can attach code to any console command execution.
use WebinoAppLib\Event\ConsoleEvent;
$app->bindConsole('my-command', function (ConsoleEvent $event) {
// obtaining console service
$cli = $event->getCli();
// obtaining command parameters
$event->getParam('myCommandArgument');
// doing something...
});
Performing action on a default console command execution.
use WebinoAppLib\Console\ConsoleDefault;
use WebinoAppLib\Event\ConsoleEvent;
$app->bindConsole(ConsoleDefault::class, function (ConsoleEvent $event) {
// do something...
});
See also
Command Parameters¶
Obtaining command parameters.
/** @var \WebinoAppLib\Event\ConsoleEvent $event */
$value = $event->getParam('myCommandArgument');
Arguments¶
Arguments are expected to appear on the command line exactly the way they are spelled in the route.
Providing required argument alternatives.
'my-command (requiredArgumentA|requiredArgumentB)'
Required and optional argument values.
'my-command <requiredArgumentValue> [<optionalArgumentValue>]'
Providing optional argument alternatives.
'my-command [optionalArgumentA|optionalArgumentB]'
Options¶
You can define any number of optional and required options. The order of options is ignored. They can be defined in any order and the user can provide them in any other order.
Providing required option alternatives.
'my-command (--requiredOptionA|--requiredOptionB)'
Optional option and its short alternative.
'my-command [--optionalOption|-o]'
Options can digest text-based values.
'my-command --requiredOptionValue= [--optionalOptionValue=]'
Console Config¶
Console¶
Configuring console command routes.
use WebinoAppLib\Application\CoreConfig;
use WebinoAppLib\Feature\Route\Console;
Webino::config([
(new Console('my-basic-command'))
->setRoute('my-command')
->setTitle('My command title'),,
(new Console('my-extra-command'))
->setRoute('my-command <requiredArgumentValue> --requiredOptionValue=')
->setTitle('My command title')
->setDescription([
'My extra command',
'multi-line description.',
])
->setArgumentsDescription([
'requiredArgumentValue' => 'Enter custom argument value',
])
->setOptionsDescription([
'requiredOptionValue=' => 'Enter custom option value',
]),
]);
Console Interface¶
- $app->bindConsole()
- Console Event
- $cli->out()
- $cli->inline()
- $cli->columns()
- $cli->table()
- $cli->json()
- $cli->sp()
- $cli->br()
- $cli->tab()
- $cli->draw()
- $cli->border()
- $cli->dump()
- $cli->flank()
- $cli->progress()
- $cli->padding()
- $cli->animation()
- $cli->addArt()
- $cli->clear()
- Colors
- Background Colors
- Text Style
- Style Commands
- User Input
$app->bindConsole()¶
Binding to console commands.
use WebinoAppLib\Event\ConsoleEvent;
$app->bindConsole('my-command', function (ConsoleEvent $event) {
// obtaining console service
$cli = $event->getCli();
// obtaining command parameters
$event->getParam('myCommandArgument');
// doing something...
});
See also
Console Event¶
$event->getCli()¶
Obtaining the console service from the console event object.
use WebinoAppLib\Event\ConsoleEvent;
$consoleEventHandler = function (ConsoleEvent $event) {
$cli = $event->getCli();
};
See also
Fluent interface:
// Method chaining
$cli->red('Red text!')->green('Green text!');
// If you prefer, you can also simply chain
// the color method and continue using out.
$cli->blue()->out('Blue? Wow!');
$event->getParam()¶
Accessing command arguments/options.
/** @var \WebinoAppLib\Event\ConsoleEvent $event */
$value = $event->getParam('myCommandArgument');
See also
$cli->inline()¶
Printing text inline to the terminal, without ending line break.
$cli->inline('Inline console text!');
$cli->columns()¶
List out an array of data so that it is easily readable.
$data = [
'12 Monkeys',
'12 Years a Slave',
'A River Runs Through It',
'Across the Tracks',
'Babel',
'Being John Malkovich',
'Burn After Reading',
'By the Sea',
'Confessions of a Dangerous Mind',
'Contact',
'Cool World',
'Cutting Class',
'Fight Club',
'Fury',
'Happy Feet Two',
'Happy Together',
'Hunk',
'Inglourious Basterds',
'Interview with the Vampire',
'Johnny Suede',
'Kalifornia',
'Killing Them Softly',
'Legends of the Fall',
'Less Than Zero',
'Meet Joe Black',
'Megamind',
'Moneyball',
];
$cli->columns($data);
Specify the number of columns by passing in a second parameter.
$cli->columns($data, 4);
Note
Console service will try to figure out how the content best fits in your terminal by default.
Specify the columns via an array of arrays.
$data = [
['Gary', 'Mary', 'Larry', 'Terry'],
[1.2, 4.3, 0.1, 3.0],
[6.6, 4.4, 5.5, 3.3],
[9.1, 8.2, 7.3, 6.4],
];
$cli->columns($data);
See also
$cli->table()¶
Make table out of an array of data so that it is easily readable.
$data = [
[
'Walter White',
'Father',
'Teacher',
],
[
'Skyler White',
'Mother',
'Accountant',
],
[
'Walter White Jr.',
'Son',
'Student',
],
];
$cli->table($data);
If you pass in an array of associative arrays or objects, the keys will automatically become the header of the table.
$data = [
[
'name' => 'Walter White',
'role' => 'Father',
'profession' => 'Teacher',
],
[
'name' => 'Skyler White',
'role' => 'Mother',
'profession' => 'Accountant',
],
[
'name' => 'Walter White Jr.',
'role' => 'Son',
'profession' => 'Student',
],
];
$cli->table($data);
See also
$cli->json()¶
Printing pretty-printed JSON to the terminal.
$cli->json([
'name' => 'Gary',
'age' => 52,
'job' => 'Engineer',
]);
See also
$cli->sp()¶
Printing spaces to the terminal.
$cli->sp();
// many at once
$cli->sp(3);
// method chaining
$cli->sp()->out('I have moved right a space.');
$cli->br()¶
Printing line breaks to the terminal.
$cli->br();
// many at once
$cli->br(3);
// method chaining
$cli->br()->out('I have moved down a line.');
$cli->tab()¶
Printing tabulators to the terminal.
$cli->tab();
// many at once
$cli->tab(3);
// method chaining
$cli->tab()->out('I am all sorts of indented.');
$cli->draw()¶
Drawing some ASCII art.
$cli->draw('bender');
Note
You can add custom ASCII art using the addArt
method.
See also
$cli->addArt() ● Console Draw Example ● Console Add Art Example
$cli->border()¶
Inserting borders to break up output. Outputs a dashed border by default.
$cli->border();
// character(s) to be repeated
$cli->border('*');
// length of the border
$cli->border('*', 50);
See also
$cli->dump()¶
Dumping variables out to the terminal.
$cli->dump([
'This',
'That',
'Other Thing',
]);
See also
$cli->flank()¶
Bringing a little more attention to text.
$cli->flank('Look at me. Now.');
// specifying the flanking characters
$cli->flank('Look at me. Now.', '!');
// and how many flanking characters there should be
$cli->flank('Look at me. Now.', '!', 5);
See also
$cli->progress()¶
Adding progress bars to the terminal.
$progress = $cli->progress()->total(100);
// or shorthand it and pass the total
// right into the progress method
$progress = $cli->progress(100);
for ($i = 0; $i <= 100; $i++) {
$progress->current($i);
// simulate something happening
usleep(rand(10000, 300000));
}
You can also manually advance the bar.
$progress = $cli->progress(100);
// do something..
$progress->advance(); // adds 1 to the current progress
// do something..
$progress->advance(10); // adds 10 to the current progress
// do something..
$progress->advance(5, 'Still going.'); // adds 5, displays a label
Pass a label into the current
method if you’d like a more descriptive indicator of where you are in the process.
$items = [
'php',
'javascript',
'python',
'ruby',
'java',
];
$progress = $cli->progress(count($items));
foreach ($items as $key => $value) {
$progress->current($key + 1, $value);
// simulate something happening
usleep(rand(10000, 300000));
}
See also
$cli->padding()¶
Padding out a string to a specified length, allowing for neatly organized data.
$padding = $cli->padding(20);
// or specify the padding character(s)
$padding = $cli->padding(20, '-');
$padding->label('Eggs')->result('1.99€');
$padding->label('Oatmeal')->result('4.99€');
$padding->label('Bacon')->result('2.99€');
See also
$cli->animation()¶
Taking ASCII art and running basic animations on it in the terminal. Valid directions are left
, top
, right
and bottom
.
// movement
$cli->animation('bender')->enterFrom('left');
$cli->animation('bender')->exitTo('left');
// scrolling
$cli->animation('bender')->scroll('left');
Altering the speed of the animation. The parameter should be an integer representing the percentage of the default speed.
// animate twice as fast
$cli->animation('bender')->speed(200)->scroll('left');
Note
50
would make it slower by half, whereas 200
would make it run at twice the speed.
You can create a directory of text files that represent each keyframe in an animation
my/
folder/
animation/
custom-animation-01.txt
custom-animation-02.txt
custom-animation-03.txt
and just run it manually.
$cli->addArt('my/folder/custom-animation');
$cli->animation('custom-animation')->run();
Note
You can add custom ASCII art using the addArt
method.
$cli->addArt()¶
Adding your own art by setting the directory in which it is located.
my/
folder/
art/
dog.txt
cat.txt
mug.txt
Let the console service know where it is via the full path.
$cli->addArt('my/folder/art');
Now you can use anything in that directory.
$cli->draw('dog');
$cli->red()->draw('cat');
$cli->red()->bold()->draw('mug');
You can style your art using tags:
<blue> ( )</blue>
<blue> H</blue>
<blue> H</blue>
<blue> _H_</blue>
<blue> .-'-.-'-.</blue>
<blue> / \</blue>
<blue>| |</blue>
<blue>| .-------'._</blue>
<blue>| /<white>/ '.' '.</white> \</blue>
<blue>| \<white>\ <black><red>@ @</red></black> /</white> /</blue>
<blue>| '---------'</blue>
<blue>| _______|</blue>
<blue>| .'<black>-+-+-+</black>|</blue>
<blue>| '.<black>-+-+-+</black>|</blue>
<blue>| """""" |</blue>
<blue>'-.__ __.-'</blue>
<blue> """</blue>
See also
$cli->draw() ● $cli->animation() ● Console Add Art Example ● Console Draw Example
Colors¶
See also
$cli->lightGray()¶
Printing text in light gray color to the terminal.
$cli->lightGray('Light gray text!');
$cli->darkGray()¶
Printing text in dark gray color to the terminal.
$cli->darkGray('Dark gray text!');
$cli->lightRed()¶
Printing text in light red color to the terminal.
$cli->lightRed('Light red text!');
$cli->lightGreen()¶
Printing text in light green color to the terminal.
$cli->lightGreen('Light green text!');
$cli->lightYellow()¶
Printing text in light yellow color to the terminal.
$cli->lightYellow('Light yellow text!');
$cli->lightBlue()¶
Printing text in light blue color to the terminal.
$cli->lightBlue('Light blue text!');
$cli->lightMagenta()¶
Printing text in light magenta color to the terminal.
$cli->lightMagenta('Light magenta text!');
$cli->lightCyan()¶
Printing text in light cyan color to the terminal.
$cli->lightCyan('Light cyan text!');
Background Colors¶
See also
$cli->blackBg()¶
Printing text on black background color to the terminal.
$cli->blackBg('Text on black background!');
$cli->redBg()¶
Printing text on red background color to the terminal.
$cli->redBg('Text on red background!');
$cli->greenBg()¶
Printing text on green background color to the terminal.
$cli->greenBg('Text on green background!');
$cli->yellowBg()¶
Printing text on yellow background color to the terminal.
$cli->yellowBg('Text on yellow background!');
$cli->blueBg()¶
Printing text on blue background color to the terminal.
$cli->blueBg('Text on blue background!');
$cli->magentaBg()¶
Printing text on magenta background color to the terminal.
$cli->magentaBg('Text on magenta background!');
$cli->cyanBg()¶
Printing text on cyan background color to the terminal.
$cli->cyanBg('Text on cyan background!');
$cli->grayBg()¶
Printing text on light gray background color to the terminal.
$cli->grayBg('Text on light gray background!');
$cli->darkGrayBg()¶
Printing text on dark gray background color to the terminal.
$cli->darkGrayBg('Text on dark gray background!');
$cli->lightRedBg()¶
Printing text on light red background color to the terminal.
$cli->lightRedBg('Text on light red background!');
$cli->lightGreenBg()¶
Printing text on light green background color to the terminal.
$cli->lightGreenBg('Text on light green background!');
$cli->lightYellowBg()¶
Printing text on light yellow background color to the terminal.
$cli->lightYellowBg('Text on light yellow background!');
$cli->blueBg()¶
Printing text on light blue background color to the terminal.
$cli->blueBg('Text on light blue background!');
$cli->magentaBg()¶
Printing text on light magenta background color to the terminal.
$cli->magentaBg('Text on light magenta background!');
$cli->cyanBg()¶
Printing text on light cyan background color to the terminal.
$cli->cyanBg('Text on light cyan background!');
$cli->whiteBg()¶
Printing text on white background color to the terminal.
$cli->whiteBg('Text on white background!');
Text Style¶
See also
$cli->invert()¶
Printing inverted colors text to the terminal.
$cli->invert('Inverted colors text!');
Style Commands¶
See also
$cli->comment()¶
Printing text in a comment style to the terminal.
$cli->comment('Comment text style!');
$cli->whisper()¶
Printing text in a whisper style to the terminal.
$cli->whisper('Whisper text style!');
User Input¶
$cli->input()¶
Getting text from a user.
// basic input
$input = $cli->input('How you doin?');
$result = $input->prompt();
// multi-line input
$input = $cli->input('>>>')->multiLine();
$result = $input->prompt();
Note
Multi-line input will wait for CTRL+D
before returning.
Specifying certain answers from the user you only want to accept (case insensitive).
$input = $cli->input('How you doin?')->accept(['Fine', 'Ok']);
$result = $input->prompt();
// or showing expecting answers
$input = $cli->input('How you doin?')->accept(['Fine', 'Ok'], true);
$result = $input->prompt();
Note
User will be re-prompted until responds with an acceptable answer.
Expecting answers exactly as they are specified (case sensitive).
$input = $cli->input('How you doin?')->accept(['Fine', 'Ok'])->strict();
$result = $input->prompt();
Note
Answering fine
or ok
will cause a re-prompt.
Passing a closure into the accept
method.
$input = $cli->input('How you doin?');
$input->accept(function($result) {
return ('Fine' === $result);
});
$result = $input->prompt();
Specifying a default response for when the user simply presses enter
without typing anything in.
$input = $cli->input('How you doin?')->defaultTo('Great!');
$result = $input->prompt();
See also
$cli->confirm()¶
Prompting the user for y
or n
(strict).
$input = $cli->confirm('Continue?');
if ($input->confirmed()) {
// do something...
}
See also
$cli->password()¶
Hiding text the user is typing.
$input = $cli->password('Please enter password:');
$pwd = $input->prompt();
See also
$cli->checkboxes()¶
Presenting the user with a set of interactive options. The user can select multiple of them.
$options = ['Ice Cream', 'Mixtape', 'Teddy Bear', 'Pizza', 'Puppies'];
// or as associative array
$options = [
'option1' => 'Ice Cream',
'option2' => 'Mixtape',
'option3' => 'Teddy Bear',
'option4' => 'Pizza',
'option5' => 'Puppies'
];
$input = $cli->checkboxes('Please send me all of the following:', $options);
$result = $input->prompt();
You will get an array back with the checked options (an empty array in the case of no checked options). If you provide an associative array as the options, an array of the selected keys will be provided as the result.
See also
$cli->radio()¶
Presenting the user with a set of interactive options. The user can only select one of them.
$options = ['Ice Cream', 'Mixtape', 'Teddy Bear', 'Pizza', 'Puppies'];
// or as associative array
$options = [
'option1' => 'Ice Cream',
'option2' => 'Mixtape',
'option3' => 'Teddy Bear',
'option4' => 'Pizza',
'option5' => 'Puppies'
];
$input = $cli->radio('Please send me one of the following:', $options);
$result = $input->prompt();
The result will be a string, not an array (the selected key in the case of an associative array).
See also
Commands Schedule¶
TODO…
Advanced Styling¶
Combinations¶
Chaining any of the style to get what you want.
$cli->blueBg()->green()->bold()->out('Fusce eget faucibus eros.');
You can apply more than one format to an output, but only one foreground and one background color.
Tags¶
Applying a foreground/background color and format with tags, to just part of an output.
$cli->blue('Please <light_red>remember</light_red> to <bold><yellow>restart</yellow></bold> the server.');
You can use any of the color or formatting keywords (snake cased) as tags.
Prepend the color with background_
to use a background color tag.
$cli->blue('Please <background_light_red>remember</background_light_red> to restart the server.');