Skip to content

Command Lifecycle Hooks

Joe Huss edited this page Sep 4, 2021 · 5 revisions

Defining Application/Command Behavior

There are three methods available that commands can override, which are executed while the application runs. Don't forget to call the base implementations with parent::method()!

Method When
prepare(): bool Executed before the subcommand or this command is run. Can prevent the next command from running by returning false.
execute(): bool Executed only if there are no more subcommands. Cannot be overridden in an application.
finish(): void Executed after the subcommand or this command is run.

When making use of subcommands, this results in a call tree that looks like this:

command->prepare()
    subcommand1->prepare()
        subcommand2->prepare()
        subcommand2->execute()
        subcommand2->finish()
    subcommand1->finish()
command->finish()

The execute method can have arguments defined which will be filled with the arguments from the command line. Example:

program command valueA valueB
public function execute($first, $customName, $optional = "valueX") {
    //$first == "valueA"
    //$customName == "valueB"
    //$optional == "valueX"
}

Listening for events externally

You can call $app->getEventService()->register($eventName, $callable) to register callbacks for events. The callbacks won't receive any arguments, so they won't have any context. The following events are available:

Event When
execute.before Before the execute() method is called and the execute event is fired.
execute Before the execute() method is called, but after the execute.before event is fired.
execute.after After the execute() method is called.