Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

CLI scripts

From MoodleDocs
Revision as of 13:38, 14 July 2021 by David Mudrak (talk | contribs) (Text replacement - "<code php>" to "<syntaxhighlight lang="php">")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

Example

<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Moodle CLI script - demo.php
 *
 * @package     plugintype_pluginname
 * @copyright   2019 Your Name <email@example.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

define('CLI_SCRIPT', true);

require(__DIR__ . '/../../../config.php');
require_once($CFG->libdir . '/clilib.php');

$usage = "Put a one line summary of what the script does here.

Usage:
    # php demo.php --paramname=<value>
    # php demo.php [--help|-h]

Options:
    -h --help               Print this help.
    --paramname=<value>     Describe the parameter and the meaning of its values.
";

list($options, $unrecognised) = cli_get_params([
    'help' => false,
    'paramname' => null,
], [
    'h' => 'help'
]);

if ($unrecognised) {
    $unrecognised = implode(PHP_EOL . '  ', $unrecognised);
    cli_error(get_string('cliunknowoption', 'core_admin', $unrecognised));
}

if ($options['help']) {
    cli_writeln($usage);
    exit(2);
}

if (empty($options['paramname'])) {
    cli_error('Missing mandatory argument paramname.', 2);
}

// Do something useful here.