CLI (command line interface) scripts can be executed from the command line (terminal) only.
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
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).
The library clilib.php provides useful functions for basic input/output operations in CLI scripts.
- Write a text to the given stream, defaults to the standard output (since Moodle 3.0)
- Write a text followed by an end of line symbol to the given stream (since Moodle 3.0)
- Prompt the user for an input value
- Parse and return arguments passed to the script
- Print or return section separator string
- Print or return section heading string
- Print error notification
- Print message to the standard error output and exit with the given code
- Prints ascii-graphics Moodle logo
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:
$ php do_something_useful.php --file=/path/to/file.mbz --action=validate
$ 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.
$ php do_something_useful.php -h
$ 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.