Commands

Utility class to interact with users on the command line

This manual is not finished yet!

Introduction

Pletfix includes a command line interface. It provides helpful commands for developing.

Source Hints for the Stdio Class

Stdio is a wrapper for standard input/output streams. The command uses it under the hood for the input and output methods to interact with the user.

The code comes in part from the following sources:

Running Commands

Enter this into your terminal to view a list of all available commands:

php console

Then add the command that you want to run, e.g. migrate:

php console migrate

Every command includes a help screen. For example, enter this to view available arguments and options for the migrate command:

php console migrate --help

Pletfix Console

Writing Commands

The commands are stored in the app/Commands directory. The Pletfix Application Skeleton has already placed a SampleCommand class as example in this directory.

You may run this sample by enter following command in your terminal:

php console sample:say-hello

Name and Description

The $nameproperty of the command class is the unique indicator of the command.

It could include a group, seperated with ":" from the name. The help option is therefore able to display the command list more clearly. For example, the group of this command is "sample":

/**
 * The console command name.
 *
 * @var string
 */
protected $name = 'sample:say-hello';

The $description property briefly describes what the command does. The help option displays the description when the commands are listed.

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Just a simple example.';

Arguments

The $arguments property lists all possible arguments of the command like below:

/**
 * Possible arguments of the command.
 *
 * @var array
 */
protected $arguments = [
    'name' => [
        'type'        => 'string', 
        'default'     => 'Nobody', 
        'description' => 'Name'
    ],
];

This example defines an argument named "name" and the type of this argument is string. The following types are also possible:

  • bool
  • float
  • int
  • string

The argument in the example above is optional because a default value has been set. If the default key would be omitted, the argument would be required.

Test the argument, e.g. like this:

php console sample:say-hello "Tiger Tom"

Options

Switches

The $options property holds all possible options of the command like below:

/**
 * Possible options of the command.
 *
 * @var array
 */
protected $options = [
    'bye' => [
        'type'        => 'bool', 
        'short'       => 'b', 
        'description' => 'Say Good By'
    ],
];

This example defines an simple switch named "bye" with the shortcut "b". The type of this option is bool, a default value is not required and would be ignored.

As common usual, the options are indicated with two minus signs:

php console sample:say-hello --bye

Most options provide a shortcut, which are start with just one minus sign. In our example, this looks like this:

php console sample:say-hello -b

Options With Values

Furthermore, you may define options as float, int and string like this:

protected $options = [
    'rating' => [
        'type'        => 'int', 
        'short'       => 'r',
        'default'     => 0,
        'description' => 'Your Rating between 1 and 10'
    ],
];

The user must specify a value for this option by running the command, such as:

php console jury --rating=32

Of course, for float, int and string types, it is useful to define a default value, unless the default should be null.

Handle

The handle method is your entry point for coding. To understand what happens under the hood, study the Lifecycle.

You may use the most services in the same way as in your web application because the console runs in a simillar context. Additional, the Command class provides a variety of methods to interact with the user.

/**
 * Execute the console command.
 */
public function handle()
{
    if ($this->input('bye')) {
        $this->line('Good by, ' . $this->input('name') . '.');
    }
    else {
        $this->line('Hello ' . $this->input('name') . '.');
    }
}

Termination Signal

You can determine if a SIGTERM signal has been triggered to terminate the process like this:

public function handle()
{
    while (!$this->isTerminated()) {
        // do whatever you want
    }
}            

To send a SIGTERM signal (15) to PID 1234 enter this into your terminal:

kill -15 1234

See also process->terminate().

Exit Code

The return value of the handle method should be the exit code for the command.

For conventional reasons you could returns also nothing or true. In this case the exit code of the command will be static::EXIT_SUCCESS (equal 0).

And if the return value is false, the exit code will be converted to static::EXIT_FAILURE (equal 1).

Help Screen

It's poosible to extends the default help screen:

/**
 * Print the Help
 */
public function printHelp()
{
    parent::printHelp();

    $this->notice('Importend Notice!');
    $this->line('Lorem ipsum dolor sit amet, consectetur, adipisci velit.');
}

Do not forget calling parent::printHelp();!

Available Methods

Input

Output

Miscellaneous

Method Listing

Input

ask()

Prompts the user for input, and returns it.

public function ask($prompt, $default = null);

choice()

/**
 * Prompts the user for input based on a list of options, and returns it.
 *
 * @param string $prompt Prompt text.
 * @param array $options Array of options.
 * @param string|null $default Default input value.
 * @return mixed Either the default value, or the user-provided input.
 */
public function choice($prompt, $options, $default = null);

confirm()

/**
 * Asking for Confirmation
 *
 * If you need to ask the user for a simple confirmation, you may use the confirm method. By default, this method
 * will return false. However, if the user enters y or yes in response to the prompt, the method will return true.
 *
 * @param string $prompt Prompt text.
 * @param boolean $default Default input value, true or false.
 * @return mixed Either the default value, or the user-provided input.
 */
public function confirm($prompt, $default = false);

read()

/**
 * Prompts the user for input, and returns it.
 *
 * @param string $prompt Prompt text.
 * @param string|array|null $options String of options, e.g. ['y' => 'yes', 'n' => 'no'].  Pass null to omit.
 * @param string|null $default Default input value. Pass null to omit.
 * @return string Either the default value, or the user-provided input.
 */
public function read($prompt, $options = null, $default = null);

secret()

/**
 * Asks a question with the user input hidden.
 *
 * The secret method is similar to ask, but the user's input will not be visible to them as they type in the console.
 * This method is useful when asking for sensitive information such as a password.
 *
 * The function will run only on a unix like system (linux or mac).
 *
 * @param string $prompt Prompt text.
 * @param string|null $default Default input value.
 * @return mixed Either the default value, or the user-provided input.
 */
public function secret($prompt, $default = null);

Output

debug()

/**
 * Output at the debug level.
 *
 * @param string $text
 * @param array $styles Combination of Stdio::STYLE constants
 */
public function debug($text, array $styles = []);

error()

/**
 * Write an error text.
 *
 * @param string $text
 */
public function error($text);

format()

/**
 * Format text.
 *
 * @param string $text The message
 * @param array $styles Combination of Stdio::STYLE constants
 * @return string
 */
public function format($text, array $styles = []);

hr()

/**
 * Outputs a series of minus characters to the standard output, acts as a visual separator.
 *
 * @param int $width Width of the line, defaults to 79
 */
public function hr($width = 79);

info()

/**
 * Write a information.
 *
 * @param string $text
 */
public function info($text);

line()

/**
 * Write standard text.
 *
 * @param string $text
 */
public function line($text);

notice()

/**
 * Write a notice.
 *
 * @param string $text
 */
public function notice($text);

question()

/**
 * Write a question.
 *
 * @param string $text
 */
public function question($text);

quiet()

/**
 * Output at the quiet level.
 *
 * @param string $text
 * @param array $styles Combination of Stdio::STYLE constants
 */
public function quiet($text, array $styles = []);

verbose()

/**
 * Output at the verbose level.
 *
 * @param string $text
 * @param array $styles Combination of Stdio::STYLE constants
 */
public function verbose($text, array $styles = []);

Verbosity of Messages

Change verbosity of messages

php console sample:say-hello --verbose=2

0=quiet, 1=normal, 2=verbose, 3=debug

warn()

/**
 * Write a warning.
 *
 * @param string $text
 */
public function warn($text);

write()

/**
 * Write a formatted text o standard output.
 *
 * @param string $text The message
 * @param bool $newline Whether to add a newline
 * @param array $styles Combination of Stdio::STYLE constants
 * @param int $verbosity Determine if the output should be only at the verbose level
 */
public function write($text, $newline = false, array $styles = [], $verbosity = Stdio::VERBOSITY_NORMAL);

Miscellaneous

arguments()

/**
 * Possible arguments of the command.
 *
 * This is an associative array where the key is the argument name and the value is the argument attributes.
 * Each attribute is a array with following values:
 * - type:        (string) The data type (bool, float, int or string).
 * - default:     (mixed)  The default value for the argument. If not set, the argument is required.
 * - description: (string) The description of the argument. Default: null
 *
 * @return array
 */
public function arguments();

clearTerminal()

/**
 * Clear the teminal screen.
 */
public function clearTerminal();

description()

/**
 * The console command description.
 *
 * @return string
 */
public function description();

input()

/**
 * Get the input value.
 *
 * @param string $key
 * @return array
 */
public function input($key);

isDebug()

/**
 * Returns whether verbosity is debug (-vv).
 *
 * @return bool true if verbosity is set to VERBOSITY_DEBUG, false otherwise
 */
public function isDebug();

isQuiet()

/**
 * Returns whether verbosity is quiet (-q).
 *
 * @return bool true if verbosity is set to VERBOSITY_QUIET, false otherwise
 */
public function isQuiet();

isVerbose()

/**
 * Returns whether verbosity is verbose (-v) or debug (-vv).
 *
 * @return bool true if verbosity is set to VERBOSITY_VERBOSE or VERBOSITY_DEBUG, false otherwise
 */
public function isVerbose();

name()

/**
 * The console command name.
 *
 * @return string
 */
public function name();

options()

/**
 * Possible options of the command.
 *
 * This is an associative array where the key is the option name and the value is the option attributes.
 * Each attribute is a array with following values:
 * - type:        (string) The data type (bool, float, int or string).
 * - short:       (string) Alternative option name.
 * - default:     (mixed)  The default value for the option. If the default value is not set and the type is not bool, the option is required.
 * - description: (string) The description of the option. Default: null
 *
 * @return array
 */
public function options();

stdio()

Returns a Stdio instance, a Standard Input/Output stream to interact with the user.

$stdio = $this->stdio();

Stdio provides methods for input and output messages. The basically method for outputting messages is write. All other messages that output messages used this function. And the basically input method is read, which is used by all functions that get the users input (except: secret).

You can access the most of the methods of the Stdio class directly from the AbstractCommand so you normally do not need the roundabout way over stdio(). Exception are the following functions which are not served by the command class:

$stdio->err($text);           // Prints text to Standard Error.
$stdio->getStdin();           // Returns the Standard Input handle.     
$stdio->setStdin($stdin);     // Set a Standard Input handle    
$stdio->getStdout();          // Returns the Standard Output handle.      
$stdio->setStdout($stdout);   // Set a Standard Output handle       
$stdio->getStderr();          // Returns the Standard Error handle.       
$stdio->setStderr($stderr);   // Set a Standard Error handle.       
$stdio->setVerbosity($level); // Sets the verbosity (one of the Stdio::VERBOSITY constants).       
$stdio->getVerbosity();       // Gets the current verbosity (one of the Stdio::VERBOSITY constants).

Styles

The style constants of Stdio class based on the ANSI/VT100 Terminal Control reference.

const STYLE_BOLD       = 1;
const STYLE_DIM        = 2;
const STYLE_UL         = 4;
const STYLE_BLINK      = 5;
const STYLE_REVERSE    = 7;
const STYLE_BLACK      = 30;
const STYLE_RED        = 31;
const STYLE_GREEN      = 32;
const STYLE_YELLOW     = 33;
const STYLE_BLUE       = 34;
const STYLE_MAGENTA    = 35;
const STYLE_CYAN       = 36;
const STYLE_WHITE      = 37;
const STYLE_BLACK_BG   = 40;
const STYLE_RED_BG     = 41;
const STYLE_GREEN_BG   = 42;
const STYLE_YELLOW_BG  = 43;
const STYLE_BLUE_BG    = 44;
const STYLE_MAGENTA_BG = 45;
const STYLE_CYAN_BG    = 46;
const STYLE_WHITE_BG   = 47;

Verbose level.

const VERBOSITY_QUIET   = 0;
const VERBOSITY_NORMAL  = 1;
const VERBOSITY_VERBOSE = 2;
const VERBOSITY_DEBUG   = 3;

See also PHP's manual.

terminalHeight()

/**
 * Tries to figure out the terminal height in which this application runs.
 *
 * @return int|null
 */
public function terminalHeight();

terminalWidth()

/**
 * Tries to figure out the terminal width in which this application runs.
 *
 * @return int|null
 */
public function terminalWidth();

(edit on GitHub)