Manual:Escrevendo scripts de manutenção

This page is a translated version of the page Manual:Writing maintenance scripts and the translation is 17% complete.
Outdated translations are marked like this.

Este é um tutorial passo a passo sobre como escrever um script de manutenção baseado na classe Maintenance (consulte Maintenance.php ) que foi introduzido no MediaWiki 1.16 para tornar mais fácil escrever scripts de manutenção MediaWiki de linha de comando.

Exemplo de script

Para descrever a criação de scripts de manutenção, vamos escrever um arquivo helloWorld.php, um script que simplesmente imprime “Hello, World”. Este programa contém a quantidade mínima de código necessário para ser executado, bem como o cabeçalho de direitos autorais esperado (para cabeçalhos alternativos, consulte cabeçalhos de direitos autorais):

The below example program will print "Hello, World!".

Note that the way to invoke maintenance scripts changed in 2023 with MediaWiki 1.40, with the new run.php being used to launch all maintenance scripts, rather than directly calling them by filename (although the latter remains supported for now). This tutorial covers both methods, and notes where there are differences between the systems.

MediaWiki core

Command
$ ./maintenance/run HelloWorld
Hello, World!
Filename
maintenance/HelloWorld.php
Code
<?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!\n" );
	}
}

$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;

MediaWiki extension

Command
$ ./maintenance/run MyExtension:HelloWorld
Hello, World!
Filename
extensions/MyExtension/maintenance/HelloWorld.php
Code
<?php

namespace MediaWiki\Extension\MyExtension\Maintenance;

use 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!\n" );
	}
}

$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;

Boilerplate explained

require_once __DIR__ . "/Maintenance.php";
Incluímos Maintenance.php. Isso define o class Maintenance que tem um método para analisar argumentos, ler o console, obter o banco de dados, etc. É melhor usar o caminho completo para $3.
class HelloWorld extends Maintenance {
}
Nós substituímos a classe Maintenance e, em seguida, em
$maintClass = HelloWorld::class;
require_once RUN_MAINTENANCE_IF_MAIN;
dizemos para a classe HelloWorld executar o script usando a classe Maintenance, somente se for executado a partir da linha de comando.

Internally, RUN_MAINTENANCE_IF_MAIN loads another file doMaintenance.php which autoloads MediaWiki classes and configuration, and then runs our execute() method.

	public function execute() {
	}
A função execute() que nós fornecemos é executada.

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]
…

Análise de opções e argumentos

Cumprimentar o mundo está tudo bem, mas nós queremos ser capazes de cumprimentar as pessoas, também.

Para adicionar uma opção de linha de comando, adicione um construtor a class HelloWorld que chame addOption() de Maintenance e atualize o método execute() para usar a nova opção. 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!" );
	}

Desta vez, quando executado, a saída do script helloWorld.php muda, dependendo do argumento fornecido:

$ 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

Versão 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).

Profiling

Maintenance scripts support a --profiler option, which can be used to track code execution during a page action and report back the percentage of total code execution that was spent in any specific function. See Manual:Profiling .

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.