Skip to content

Multiple commands

Greg Bowler edited this page May 14, 2026 · 3 revisions

A single Application can host multiple commands. The first CLI argument selects the command name, and remaining arguments are parsed according to that command's declared parameters.

Creating a multi-command app

$app = new Application(
	"Multi-command example",
	new ArgumentList(...$argv),
	$sumCommand,
	$repeatCommand
);
$app->run();

In example/06-multi-command.php:

  • sum left right validates numeric input and prints a total
  • repeat text [count] repeats user text with an optional count
  • help is automatically available for global and per-command usage

Command-level errors can throw CommandException, which is caught by the application and displayed on the error stream.

if(!is_numeric($left) || !is_numeric($right)) {
	throw new CommandException("Both values must be numeric");
}

This keeps command logic focused while preserving consistent output and exit handling.

For manual error output inside a command, pass StreamName::ERROR to writeLine():

$this->writeLine("Could not read input file", StreamName::ERROR);

Commands may also return explicit exit codes from run():

  • 0 indicates success.
  • Any non-zero value exits the application with that code.

Next, refer to output streams for stream selection, or examples for complete runnable scripts.

Clone this wiki locally