Manual:Hooks/pt-br



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 sempre que   giros de gancho, passando-o a função de argumentos específicos para :

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

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 ou no seu próprio arquivo de extensão no escopo do arquivo (não na função  ou no  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. It is registered in extension.json the same way as if you were registering a built-in MediaWiki hook to use in your extension. You can then run your hook within your extension by calling. Lastly, don't forget to add them to.

Contexto
A hook is triggered by a call to HookContainer::run, usually via a method in HookRunner. HookContainer will find the hook handlers to run and call them with the parameters given to HookContainer::run. Hook handlers are registered via.

See also.

In this example from the  function in, doPurge calls HookRunner::onArticlePurge to run the  hook, passing   as argument:

The calls many hooks, but  can also call hooks.

Writing a hook handler
A hook handler is a function you register, which will be called whenever the hook in question is run.

For extensions, register your hook handlers in :

Hook handlers can also be registered via the global array. This is most commonly used for site-specific customizations in, or in legacy extensions that predate. All the following are valid ways to define a hook handler for the EventName hook, with two parameters passed:

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:

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

Hook handler return values
Event handlers can return one of three possible values:

(Before MediaWiki 1.23, returning was required.)
 * (no return value, or null) - the hook handler has operated successfully.
 * "some string" - an error occurred; processing should stop and the error should be shown to the user
 * - 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.

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

Handling hooks in MediaWiki 1.35 and later
MediaWiki 1.35 introduces a system for handling hooks based on individual hook interfaces. This system allows for dependency injection, provides machine-readable parameter names and types, and integrates hook documentation with code editors.

For extensions, methods of registering and handling hooks in MediaWiki 1.34 and earlier are not being deprecated and will continue to work as expected. Extension authors who want to pilot the new system are welcome to do so. To learn more, see the hook specification in MediaWiki Core and the announcement on wikitech-l.

 Changes to hook names 

Prior to MediaWiki 1.35, several hooks included colons in their names. With the implementation of hook interfaces, colons in hook names have been replaced with underscores. For example, the interface for ApiFeedContributions::feedItem is. This does not impact extensions using the hook system in MediaWiki 1.34 and earlier.

 Registering hooks using HookHandlers 

To register a hook in an extension's extension.json file, the new system uses HookHandlers to specify how the handler object is created. Instead of mapping a hook directly to a function, a hook maps to a HookHandlers object which specifies the  and has the option to inject.

For example, to register the BeforePageDisplay hook:

 Handling hooks using interfaces 

To work with registration using HookHandlers, extensions should define an event handler class that implements the hook interface. Hook interfaces are named with the hook name with "Hook" appended.

 Converting extensions to the new hook system  Conversion to the new system is done by doing the following for each hook handler method:
 * identify the hook handler interface, and make the hook handler class implement this interface
 * change the name and signature of the hook handler method to be exactly the same as in the interface
 * change the hook registration in the "Hooks" section of extension.json to refer to the handler you specified in the "HookHandlers" section.

The process was demonstrated at the Wikimedia Hackathon 2021:
 * Recording on YouTube
 * Patch on Gerrit

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  and   in JavaScript events, it kills other listeners for the same event).

For example, if  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.

 Before MediaWiki 1.22 

or

MediaWiki 1.22+

Documentation
Currently, hooks in MediaWiki core have to be documented both in hook interface (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.

Each hook provided by MediaWiki Core is defined in a hook interface. Typically, hook interfaces are located in a "Hook" sub-namespace inside the caller namespace. For example,. You can find a list of hook interfaces in the generated MediaWiki PHP documentation.

To document a hook on-wiki, use MediaWikiHook.

 Hook interface doc template 

In hook interfaces, doc comments specify the status, purpose, parameters, and behavior of the hook.

Hooks grouped by function
Some of these hooks can be grouped into multiple functions.
 * Sections: Article Management  -  Edit Page  -  Page Rendering  -  User Interface  -  File Management  -  Special Pages  -  User Management  -  Logging  -  Skinning Templates  -  API  -  Import/Export  -  Diffs  -  Miscellaneous

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