Open main menu
This page is a translated version of the page Manual:Hooks and the translation is 32% complete.

Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎dansk • ‎español • ‎français • ‎português do Brasil • ‎čeština • ‎български • ‎македонски • ‎русский • ‎中文 • ‎日本語 • ‎한국어
Entwicklung Tag extensions Handbuch:Parser functions Hooks Spezialseiten Handbuch:Skins Handbuch:Magische Wörter API Content models
MediaWiki extensions

Hooks allow custom code to be executed when some defined event (such as saving a page or a user logging in) occurs. For example, the following code snippet will trigger a call to the function MyExtensionHooks::pageContentSaveComplete whenever the PageContentSaveComplete hook runs, passing it function arguments specific to 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"
}

MediaWiki provides many hooks like this to extend the functionality of the MediaWiki software. Assigning a function (known as an event handler) to a hook will cause that function to be called at the appropriate point in the main MediaWiki code, to perform whatever additional task(s) the developer thinks would be useful at that point. Each hook can have multiple handlers assigned to it, in which case it will call the functions in the order that they are assigned, with any modifications made by one function passed on to subsequent functions in the chain.

Assign functions to hooks at the end of LocalSettings.php or in your own extension file at the file scope (not in a $wgExtensionFunctions function or the ParserFirstCallInit hook). For extensions, if the hook function's behavior is conditioned on a setting in LocalSettings.php, the hook should be assigned and the function should terminate early if the condition was not met.

You can also create new hooks in your own extension; if you do so, add them to the Extension hook registry.

Hintergrund

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 );

Der Core/de ruft viele Hooks auf, aber Handbuch:Erweiterungen können auch Hooks aufrufen.

Schreiben eines Ereignishandler

Ein Event-Handler ist eine Funktion, die zu einem Hook zugeordnet ist, der ausgeführt wird, wenn das Ereignis von diesem Hook vertreten auftritt wird. Es besteht aus:

  • eine Funktion mit einigen optionalen begleitenden Daten, oder
  • einer Aufgabe mit einem Verfahren und einigen optionalen zugehörigen Daten.

Eventhandler werden registriert, indem sie sie zum globalen $wgHooks Array für ein gegebenes Ereignis hinzufügen. Hooks können von jedem beliebigen Punkt in der Ausführung hinzugefügt werden, bevor der Hook aufgerufen ist, sind aber am häufigsten in LocalSettings.php hinzugefügt oder seiner enthaltenen Dateien. Alle die folgenden sind gültige Möglichkeiten, um Hooks zu definieren, mit dem Code der ausgeführt wird, wenn 'EventName' passiert:

Format Syntax Resulting function call.
Static function $wgHooks['EventName'][] = 'MyExtensionHooks::onEventName'; MyExtensionHooks::onEventName( $param1, $param2 );
Function, no data $wgHooks['EventName'][] = 'someFunction'; someFunction( $param1, $param2 );
Function with data $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"
		]
	}
}

Wenn ein Ereignis eintritt, wird die Funktion (oder Objekt-Methode) mit den optional zur Verfügung gestellten Daten sowie Event-spezifischen Parametern aufgerufen werden. Beachten Sie, dass wenn ein Objekt der Hook ist und es keine festgelegte Methode gibt, die Standard-Methode namens 'OnEventName' ist. Für verschiedene Ereignisse wäre dies anders: 'onArticleSave', 'onUserLogin', etc.

Die zusätzlichen Daten sind sinnvoll, wenn wir die gleiche Funktion oder ein Objekt für unterschiedliche Zwecke nutzen wollen. Zum Beispiel:

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

Dieser Code würde in ircNotify resultieren, zweimal zu laufen wenn ein Artikel gespeichert: einmal für 'TimStarling', und einmal für "Brion".

Event-Handler können einen von drei möglichen Werten zurückgeben:

  • no return value (or null): the hook handler has operated successfully. (Before MediaWiki 1.23, returning true was required.)
  • "some string": ein Fehler ist aufgetreten; Verarbeitung sollten aufhören, und der Fehler sollte dem Benutzer angezeigt werden
  • 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
}

Dokumentation

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}}.

Verfügbare Hooks

Für eine vollständige Liste der Hooks, benutzen Sie die Kategorie , welche mehr auf dem Laufenden gehalten werden sollte

Siehe auch