Managing command dependencies

A combination of changes we are currently working on – putting all commands into external packages as well as making the WP-CLI bootstrapping process more flexible – made it obvious that we need to deal with command dependencies in one way or another. As an example, the scaffold package command depends on the scaffold command to be already registered. Both are provided through external packages, though. If they are loaded in the wrong order, adding the scaffold package command will not work as expected.

Therefore, the current nightly includes a new mechanism for dealing with these command dependencies. This is achieved through a pair of new hooks:

Before adding a command – check requirements


The main purpose of this hook is to allow you to check runtime requirements at the moment the command would be added.

The callback you provide will have a WP_CLI\Dispatcher\CommandAddition object be provided as the first argument. This object has a method abort( $reason ) that you can use to prevent the command from being added. The reason that you provide is not yet being used, but the plan is to display this reason in the help screen so that users have feedback about why certain commands are unavailable.

Usage example:

WP_CLI::add_hook( 'before_add_command:db', function ( $addition ) {
    if ( ! $this->database_is_available() ) {
            'The db command needs a working connection to the database.'
} );

After adding a command – load dependent commands


This hook is used to have one command depend on a different command being loaded first. The main use case is when you add a new sub-command to a parent command located in a different package. As you cannot simply depend on loading order, you can wrap the addition of this sub-command in the after_add_command:<command>  hook.

Usage example:

WP_CLI::add_hook( 'after_add_command:scaffold', function () {
    WP_CLI::add_command( 'scaffold package', 'WP_CLI\ScaffoldPackageCommand' );
} );

Future considerations

These two hooks allow commands to be built in a more robust way and open up new possibilities for the future.

One of the goals we currently discuss is to have the help screen display unavailable commands together with the reason why the command has been disabled. This provides valuable feedback to the user and might even point to the next action for resolving the issue.

Also, getting rid of some of the run-time errors that let WP-CLI fail without even showing a help screen can potentially be defused through these hooks as well. A simple requirements check before adding a command can then display a warning, and avoid adding the command that would throw an error.