Посібник:Написання скриптів обслуговування
Це покроковий посібник із написання скрипта обслуговування на основі класу Maintenance
(див. Maintenance.php ), який був представлений у MediaWiki 1.16, щоб полегшити написання сценаріїв обслуговування MediaWiki командного рядка.
Boilerplate
Створимо власний допоміжний скрипт helloWorld.php
, який буде просто друкувати фразу «Hello, World». У цьому скрипті буде мінімум коду, а також заголовок-коментар із застереженням про авторське право (див. усі заголовки-ліцензії):
The below example program will print "Hello, World!":
$ php helloWorld.php Hello, World!
MediaWiki core
<?php
require_once __DIR__ . '/Maintenance.php';
/**
* Brief oneline description of Hello world.
*
* @since 1.17
* @ingroup Maintenance
*/
class HelloWorld extends Maintenance {
public function execute() {
$this->output( 'Hello, World!' );
}
}
$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;
MediaWiki extension
<?php
namespace MediaWiki\Extension\Example\Maintenance;
$IP = getenv( 'MW_INSTALL_PATH' );
if ( $IP === false ) {
$IP = __DIR__ . '/../../..';
}
require_once "$IP/maintenance/Maintenance.php";
/**
* Brief oneline description of Hello world.
*/
class HelloWorld extends Maintenance {
public function __construct() {
parent::__construct();
$this->requireExtension( 'Extension' );
}
public function execute() {
$this->output( 'Hello, World!' );
}
}
$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;
Boilerplate explained
require_once __DIR__ . "/Maintenance.php";
Оскільки це допоміжний скрипт, то ми підключаємо файл Maintenance.php
. Він подбає за автозавантаження класів тощо. Найкраще слід використовувати повний шлях до файлу $3.
class HelloWorld extends Maintenance {
- Розширюємо клас Maintenance, а потім з
$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;
Вказуємо, що при запуску файлу має Maintenance клас HelloWorld
і лише тоді, якщо скрипт запущено з командного рядка (а не з браузера).
Internally, RUN_MAINTENANCE_IF_MAIN
loads another file doMaintenance.php which autoloads MediaWiki classes and configuration, and then
public function execute() {
The execute()
method is the entrypoint for maintenance scripts, and is where the main logic of your script will be. Avoid running any code from the constructor.
When our program is run from the command-line, the core maintenance framework will take care of initialising MediaWiki core and configuration etc, and then it will invoke this method.
Help command
One of the built-in features that all maintenance scripts enjoy is a --help
option. The above example boilerplate would produce the following help page:
$ php helloWorld.php --help Usage: php helloWorld.php […] Generic maintenance parameters: --help (-h): Display this help message --quiet (-q): Whether to suppress non-error output --conf: Location of LocalSettings.php, if not default --wiki: For specifying the wiki ID --server: The protocol and server name to use in URL --profiler: Profiler output format (usually "text") …
Adding a description
"But what is this maintenance script for?" I can hear you asking.
We can put a description at the top of the "--help
" output by using the addDescription
method in our constructor:
public function __construct() {
parent::__construct();
$this->addDescription( 'Say hello.' );
}
The output now gives us the description:
$ php helloWorld.php --help Say hello. Usage: php helloWorld.php [--help] …
Розбір параметрів і аргументів
Привітання усім одразу — це добре, але ми також хочемо надсилати привіт і окремим користувачам.
Щоб передавати параметри скриптові, слід додати конструктор і в ньому викликати метод addOption()
. Крім того, треба внести зміни до функції execute()
.
addOption()
's parameters are $name, $description, $required = false, $withArg = false, $shortName = false
, so:
public function __construct() {
parent::__construct();
$this->addDescription( 'Say hello.' );
$this->addOption( 'name', 'Who to say Hello to', false, true );
}
public function execute() {
$name = $this->getOption( 'name', 'World' );
$this->output( "Hello, $name!" );
}
На цей раз, коли виконується, вихід із скриптів змін helloWorld.php
залежно від аргументу, якщо:
$ php helloWorld.php Hello, World! $ php helloWorld.php --name=Mark Hello, Mark! $ php helloWorld.php --help Say hello. Usage: php helloWorld.php […] … Script specific parameters: --name: Who to say Hello to
Extensions
Версія MediaWiki: | ≥ 1.28 Gerrit change 301709 |
If your maintenance script is for an extension, then you should add a requirement that the extension is installed:
public function __construct() {
parent::__construct();
$this->addOption( 'name', 'Who to say Hello to' );
$this->requireExtension( 'FooBar' );
}
This provides a helfpul error message when the extension is not enabled. For example, during local development a particular extension might not yet be enabled in LocalSettings.php, or when operating a wiki farm an extension might be enabled on a subset of wikis.
Be aware that no code may be executed other than through the execute()
method.
Attempts to call MediaWiki core services, classes, or functions, or calling your own extension code prior to this, will cause errors or is unreliable and unsupported (e.g. ouside the class declaration, or in the constructor).
Writing tests
It's recommended to write tests for your maintenance scripts, like with any other class. See the Maintenance scripts guide for help and examples.