Skip to content
Bertie2011 edited this page Aug 29, 2021 · 1 revision

Instead of repeating the same logic in multiple commands, you can register those commands as subcommands on the parent command that executes the reused logic. For example, a file command could be used to select files and then several subcommands could be used to print, copy, move or delete those files.

program file -f ~/a.txt -f ~/b.txt -f ~/c.txt delete
program file -f ~/a.txt -f ~/b.txt -f ~/c.txt copy ~/folder/
program file -f ~/a.txt -f ~/b.txt -f ~/c.txt move ~/folder/
program file -f ~/a.txt -f ~/b.txt -f ~/c.txt print

Before you start, there are a few things to note:

  • Options can only be used for the (sub)command that they are registered in.
    So program [command1] [command2] [options for command1] is not allowed,
    while program [command1] [options for command 1] [command2] is.
  • Only the last (sub)command can have arguments. In other words, any command with subcommands cannot receive arguments.

Start by overriding the public function init(): void method and make sure to call parent::init(). Then call $this->addCommand('name', MyCommand::class) to register the subcommand.

You can also register multiple commands in a group using $this->addCommandGroup('group', ['name' => MyCommand::class, ...]), to categorize them in the help output.

Prefix the name with a _ to hide the command from the help menu.

A command can override the public function aliases(): string[] method to return aliases for the command, which will be registered by CLIFramework. They won't show up in the help output of the parent command, but will in the help output of the command that has the aliases.

Subcommands can get data from their parent commands using $this->getParent().

Clone this wiki locally