Manual:Hooks/ru



Хуки позволяют выполнять собственный код, при возникновении определенного события (например, сохранение страницы или вход пользователя). Например, следующий фрагмент кода вызовет функцию  всякий раз, когда выполняется хук , передавая ему аргументы функции, специфичные для $PageContentSaveComplete: For example, the following code snippet will trigger a call to the function whenever the   hook runs, passing it function arguments specific to.

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

MediaWiki предоставляет множество хуков для расширения функциональности программного обеспечения MediaWiki. Назначение функции (известной как обработчик событий) на хук приведет к вызову этой функции в соответствующей точке основного кода MediaWiki для выполнения каких-либо дополнительных задач, которые, по мнению разработчиков, будут полезны в этот момент. Каждый хук может иметь несколько обработчиков, назначенных ему, и в этом случае он будет вызывать функции в том порядке, в котором они назначены, с любыми изменениями, внесенными одной функцией, переданной последующим функциям в цепочке. 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.

Передавайте функции хуков в конце $LocalSettings или в вашем собственном файле расширения в области файла (не в функции $wgExtensionFunctions или хука $ParserFirstCallInit). Для расширений, если поведение функций хуков обусловлено настройкой в LocalSettings.php, нужно назначить хук, и функция должна завершиться раньше, если условие не было выполнено. 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.

Вы также можете создавать новые хуки в собственном расширении; если вы это сделаете, добавьте их в реестр хуков расширений. 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.

Введение
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.

Смотрите также.

В этом примере из функции  в, doPurge вызывает HookRunner::onArticlePurge для запуска хука , передавая   в качестве аргумента:

Ядро вызывает множество хуков, но расширения также могут вызвать хуки.

Запись обработчика событий
Обработчик событий - это функция, которую вы назначаете на хук, который будет выполняться всякий раз, когда происходит событие, представленное этим хуком. Он состоит из:


 * функция с некоторыми дополнительными сопутствующими данными, или
 * объект с методом и некоторыми дополнительными сопутствующими данными.

Зарегистрируйте обработчик событий, добавив его в глобальный массив  для данного события. Хуки могут быть добавлены из любой точки выполнения до вызова хука, но чаще всего добавляются в LocalSettings.php, его включаемых файлов или для расширений в файле extension.json. Все приведенные ниже действия являются допустимыми способами определения функции хука для события EventName, которое передаётся двумя параметрами, отображающими код, который будет выполняться при возникновении EventName: Hooks can be added from any point in the execution before the hook is called, but are most commonly added in, 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:

Для расширения, синтаксис похож на синтаксис в  (соответствует первому и второму случаю выше):

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:

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:

(Before MediaWiki 1.23, returning true was required.) This will prevent further handlers from being run, and in some cases tells the calling function to skip normal processing.
 * 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
 * false: the hook handler has done all the work necessary, or replaced normal handling.

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+

Документация
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.

Хуки сгруппированные по функциям
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.

См. также

 * — specification of the hooks system
 * List of hook interfaces in MediaWiki Core
 * — contains examples of hooks
 * — the JavaScript/front-end system of hooks
 * — specification of the hooks system
 * List of hook interfaces in MediaWiki Core
 * — contains examples of hooks
 * — the JavaScript/front-end system of hooks