CLI scripts

Jump to: navigation, search

CLI (command line interface) scripts can be executed from the command line (terminal) only.

Location

It is a convention in the Moodle code that all CLI scripts are put into the cli/ folder inside the component/plugin directory.

Examples: admin/cli/, enrol/ldap/cli/, admin/tool/task/cli/ and others

CLI_SCRIPT constant

All scripts must declare themselves as CLI scripts properly by setting the CLI_SCRIPT constant before loading the main config.php file.

define('CLI_SCRIPT', true);
require(__DIR__.'/../../../config.php');

The path to the config.php must not use relative paths starting with ../. The best practise is to avoid dirname() function call and use the __DIR__ magic constant (this applies everywhere, not just for CLI scripts).

clilib.php

The library clilib.php provides useful functions for basic input/output operations in CLI scripts.

require_once($CFG->libdir.'/clilib.php');
cli_write()
Write a text to the given stream, defaults to the standard output (since Moodle 3.0)
cli_writeln()
Write a text followed by an end of line symbol to the given stream (since Moodle 3.0)
cli_input()
Prompt the user for an input value
cli_get_params()
Parse and return arguments passed to the script
cli_separator()
Print or return section separator string
cli_heading()
Print or return section heading string
cli_problem()
Print error notification
cli_error()
Print message to the standard error output and exit with the given code
cli_logo()
Prints ascii-graphics Moodle logo

Script parameters

The function cli_get_params() implements a basic cross-platform parser for the script parameters. It supports long options names (with double dashes like --version or --help) by default. Some of these long options can have short name aliases (single dashed, like -v or -h). The function does not support positional arguments for CLI scripts. Input data must be provided as a value of an option:

GOOD:

   $ php do_something_useful.php --file=/path/to/file.mbz --action=validate

BAD:

   $ php do_something_useful.php validate /path/to/file.mbz

It is a good practise that short names aliases should be used only for boolean options (flags). It is unusual in CLI environment to set values for short named options.

NICE:

   $ php do_something_useful.php -h

UGLY:

   $ php do_something_useful.php -f=/path/to/file.mbz

For documenting the expected usage of the script, you may want to use the same format and syntax as used by docopt.