Manual:Ganchos

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Manual:Hooks and the translation is 20% complete.

Outdated translations are marked like this.
Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎dansk • ‎español • ‎français • ‎português do Brasil • ‎čeština • ‎български • ‎македонски • ‎русский • ‎中文 • ‎日本語 • ‎한국어
OOjs UI icon puzzle-ltr.svg Extensões: Desenvolvimento Extensões de tags Funções do analisador sintático Hooks Páginas especiais Skins Palavras mágicas API Content models
MediaWiki extensions

Os ganchos permitem que o código personalizado seja executado quando ocorre um evento definido (como salvar uma página ou um usuário efetuando login). Por exemplo, o seguinte fragmento de código irá ativar uma chamada para a função MyExtensionHooks::pageContentSaveComplete sempre que PageContentSaveComplete giros de gancho, passando-o a função de argumentos específicos para PageContentSaveComplete:

Hooks can be registered by mapping the name of the hook to the callback in the extension's extension.json file:

"Hooks": {
    "PageContentSaveComplete": "MyExtensionHooks::onPageContentSaveComplete"
}

O MediaWiki fornece muitos ganchos como este para estender a funcionalidade do software MediaWiki. Atribuir uma função (conhecida como manipulador de eventos) para um gancho, essa função será chamada no ponto apropriado do código MediaWiki principal, para executar qualquer tarefa adicional que o desenvolvedor pense ser útil nesse ponto. Cada gancho pode ter vários manipuladores atribuídos a ele, caso em que ele chamará as funções na ordem em que são atribuídas, com quaisquer modificações feitas por uma função passada para funções subseqüentes na cadeia.

Atribua funções para encaixar no fim de LocalSettings.php ou no seu próprio arquivo de extensão no escopo do arquivo (não na função $wgExtensionFunctions ou no ParserFirstCallInit hook). Para extensões, se o comportamento da função de gancho estiver condicionado a uma configuração em LocalSettings.php, o gancho deve ser atribuído e a função deve terminar cedo se a condição não for atendida.

Você também pode criar novos ganchos em sua própria extensão; se você fizer isso, adicione-os ao Registro de gancho de extensão.

Contexto

A hook is triggered by a call to the function Hooks::run (described in file hooks.txt, and defined in GlobalFunctions.php. The first argument to Hooks::run is the name of the hook, the second is the array of arguments for that hook. It will find the event handlers to run in the array $wgHooks. It calls the PHP function call_user_func_array with arguments being the function to be called and its arguments.

See also the hook specification in core.

In this example from the doEditContent function in WikiPage.php, doEditContent calls Hooks::run to run the PageContentSaveComplete hook, passing $hookArgs as argument:

Hooks::run( 'PageContentSaveComplete', $hookArgs );

The Núcleo calls many hooks, but Extensões can also call hooks.

Writing an event handler

An event handler is a function you assign to a hook, which will be run whenever the event represented by that hook occurs. It consists of:

  • uma função com alguns dados de acompanhamento opcionais, ou
  • um objeto com um método e alguns dados acompanhantes opcionais.

Register the event handler by adding it to the global $wgHooks array for a given event. Hooks can be added from any point in the execution before the hook is called, but are most commonly added in LocalSettings.php, its included files, or, for extensions, in the file extension.json. All the following are valid ways to define a hook function for the event EventName that is passed two parameters, showing the code that will be executed when EventName happens:

Formato Sintaxe Chamada de função resultante.
Função estática $wgHooks['EventName'][] = 'MyExtensionHooks::onEventName'; MyExtensionHooks::onEventName( $param1, $param2 );
Função, sem dados $wgHooks['EventName'][] = 'someFunction'; someFunction( $param1, $param2 );
Função com dados $wgHooks['EventName'][] = [ 'someFunction', $someData ]; someFunction( $someData, $param1, $param2 );
Function, no data
(weird syntax, but OK)
$wgHooks['EventName'][] = [ 'someFunction' ]; someFunction( $param1, $param2 );
inline anonymous function
$wgHooks['EventName'][] = function( $param1, $param2 ) {
// ...function body
}
(the anonymous function is called with the hook's parameters)
Object only $wgHooks['EventName'][] = $object; $object->onEventName( $param1, $param2 );
Object with method $wgHooks['EventName'][] = [ $object, 'someMethod' ]; $object->someMethod( $param1, $param2 );
Object with method and data $wgHooks['EventName'][] = [ $object, 'someMethod', $someData ]; $object->someMethod( $someData, $param1, $param2 );
Object only
(weird syntax, but OK)
$wgHooks['EventName'][] = [ $object ]; $object->onEventName( $param1, $param2 );

For extensions, the syntax is similar in the file extension.json (corresponding to the first and second case above):

{
	"Hooks": {
		"EventName": [
			"MyExtensionHooks::onEventName",
			"someFunction"
		]
	}
}

When an event occurs, the function (or object method) that you registered will be called, the event's parameters, along with any optional data you provided at registration. Note that when an object is the hook and you didn't specify a method, the method called is 'onEventName'. For other events this would be 'onArticleSave', 'onUserLogin', etc.

The optional data is useful if you want to use the same function or object for different purposes. For example:

$wgHooks['PageContentSaveComplete'][] = [ 'ircNotify', 'TimStarling' ];
$wgHooks['PageContentSaveComplete'][] = [ 'ircNotify', 'brion' ];

This code would result in ircNotify being run twice when a page is saved: once for 'TimStarling', and once for 'brion'.

Event handlers can return one of three possible values:

  • no return value (or null): the hook handler has operated successfully. (Before MediaWiki 1.23, returning true was required.)
  • "some string": an error occurred; processing should stop and the error should be shown to the user
  • false: the hook handler has done all the work necessary, or replaced normal handling. This will prevent further handlers from being run, and in some cases tells the calling function to skip normal processing.
In many cases where an error message is expected, the hook will define a variable passed as a reference for extensions to store an error message and this is preferred over returning a string that will simply be displayed as an "internal error."

Returning false makes less sense for events where the action is complete, and will normally be ignored by the caller.

Hook behavior before MediaWiki 1.22 vs after

Extracted from: change 500542: for non-abortable hooks (most hooks) returning true has been redundant since MediaWiki 1.22 (in 2015). This was done to reduce chances of accidental failure because we had experienced several outages and broken features due to silent failures where e.g. one hook callback somewhere accidentally returned a non-bool or false instead of true/void and thus short-circuits the whole system.

(Returning non-true/non-void in a MediaWiki Hook is equivalent to e.preventDefault and e.stopImmediatePropagation in JavaScript events, it kills other listeners for the same event).

For example, if onBeforePageDisplay hook were to return false in MobileFrontend, it would mean Popups stops because its callback would no longer run. See differences below, assuming the hook onBeforePageDisplay.

Before MediaWiki 1.22

public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
    // some code
    return true; // explicit
}

or

public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
    // some code
    return; // explicit
}

MediaWiki 1.22+

public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
    // some code
    // no need for a return true or return
}


Documentation

Currently, hooks in MediaWiki core have to be documented both in docs/hooks.txt (in the source code repository) and here on MediaWiki.org. In some cases, one of these steps may not yet have been completed, so if a hook appears undocumented, check both.

To document a hook on-wiki, use {{MediaWikiHook}}.

Available hooks

For a complete list of hooks, use the category , which should be kept more up to date.

See also