Jump to content

手冊:開發擴充功能

本頁使用了標題或全文手工轉換
From mediawiki.org
This page is a translated version of the page Manual:Developing extensions and the translation is 44% complete.
Outdated translations are marked like this.
MediaWiki擴充功能

每個擴展都由三部分組成:

  1. 配置
  2. 執行
  3. 本地化

一個最小的擴展只需如下結構:

MyExtension/extension.json
存儲安裝的說明。 文件名必須為「extension.json」。 (在MediaWiki 1.25版之前,設置說明位於一個以擴展名命名的MyExtension/MyExtension.php文件中。 許多擴展在此PHP文件中仍然具有向後兼容的間隙。)
MyExtension/includes/ (or MyExtension/src/)
存儲擴展的PHP可執行代碼。
MyExtension/resources/ (or MyExtension/modules/)
存儲擴展的客戶端資源,例如JavaScript,CSS和LESS。
MyExtension/i18n/*.json
存儲擴展的本地化信息。

當您在開發擴展時,請將上文中的MyExtension替換為您開發的擴展的名字。 使用大駝峰式命名法來命名文件夾和PHP文件,這是文件命名的通常慣例。[1]BoilerPlate extension對於開發您的擴展是一個好的開始。)

開發過程中,您可能需要通過設置$wgMainCacheType = CACHE_NONE$wgCacheDirectory = false以關閉緩存,否則系統消息和其它變化可能不會出現。

設定

編寫設置部分的最終目標是使擴展安裝儘可能容易,因此用戶只需將此行添加到LocalSettings.php中:

wfLoadExtension( 'MyExtension' );

如果你要讓你的擴展是用戶可配置的,則需要定義和記錄一些配置參數,並且用戶的設置應如下所示:

wfLoadExtension( 'MyExtension' );
$wgMyExtensionConfigThis = 1;
$wgMyExtensionConfigThat = false;

為了讓這一操作變得簡單,您的設置文件需要完成許多任務(以下各節中有詳細描述):

  • 註冊您的擴展使用的所有媒體處理程序、解析器函數特殊頁面自定義XML標籤變量
  • 定義和/或驗證為擴展定義的任何配置變量。
  • 準備您的擴展程序用於自動加載的類(class)
  • 確定哪些部分需要立即完成設置,哪些部分需要在MediaWiki核心已初始化和配置後再完成設置。
  • 定義您的擴展添加的額外的
  • 創建或檢查擴展所需的任何新數據庫表。
  • 為您的擴展程序設置本地化。
Good practice is to add a README file with basic info about how to install and configure the extension. You can use either plain text or Phabricator markup syntax. For example, see the Phabricator Diffusion page for the 擴充功能:頁面表單 . If markdown is used, add the file extension .md. For example, see the README.md file for Parsoid on Phabricator Diffusion.

通過MediaWiki註冊功能

MediaWiki在其Special:Version頁面上列出了已安裝的所有擴展。 例如,您可以在Special:Version上查看此Wiki上安裝的所有擴展。

MediaWiki版本:
1.25

為此,請將擴展詳細信息添加到extension.json 。 該部分將如下所示:

{
	"name": "Example",
	"author": "John Doe",
	"url": "https://www.mediawiki.org/wiki/Extension:Example",
	"description": "This extension is an example and performs no discernible function",
	"version": "1.5",
	"license-name": "GPL-2.0-or-later",
	"type": "validextensionclass",
	"manifest_version": 1
}


許多字段都是可選的,但填寫它們仍然是一個好習慣。 manifest_version指的是extension.json 文件所針對的架構版本。 可用的版本為1和2。請參見有關此功能的文檔。 除非需要支持較舊版本的MediaWiki,否則請選擇最新版本。

除上述註冊外,您還必須將功能「鈎」到MediaWiki中。 上面僅設置了特殊:版本頁面。 執行此操作的方式取決於您開發的擴展的類型。 有關詳細信息,請參閱每種擴展類型的文檔:

使您的擴展可由用戶配置

如果您希望用戶能夠配置您的擴展程序,則需要提供一個或多個配置變量。 最好能給這些變量起一個唯一的名稱。 同樣需要遵循MediaWiki命名常規(例如,全局變量名應以$wg作為開始)。

例如,如果您擴展的名字為「MyExtension」,您可能需要將所有相關的配置變量以$wgMyExtension作為開始。 重要的是,此時MediaWiki的內核變量尚未定義,您需要做一些合理的檢查,以確保沒有已發布的擴展以這種方式開始其變量命名。 用戶不會因為您使用了重疊的變量名而在您的擴展和其它擴展之間選擇。

同樣建議在安裝說明中包括所有配置變量的詳盡文檔。

以下是一個可以用來入門的示例樣板:

{
	"name": "BoilerPlate",
	"version": "0.0.0",
	"author": [
		"Your Name"
	],
	"url": "https://www.mediawiki.org/wiki/Extension:BoilerPlate",
	"descriptionmsg": "boilerplate-desc",
	"license-name": "GPL-2.0-or-later",
	"type": "other",
	"AutoloadClasses": {
		"BoilerPlateHooks": "includes/BoilerPlateHooks.php",
		"SpecialHelloWorld": "includes/SpecialHelloWorld.php"
	},
	"config": {
		"BoilerPlateEnableFoo": {
			"value": true,
			"description": "Enables the foo functionality"
		}
	},
	"callback": "BoilerPlateHooks::onExtensionLoad",
	"ExtensionMessagesFiles": {
		"BoilerPlateAlias": "BoilerPlate.i18n.alias.php"
	},
	"Hooks": {
		"NameOfHook": "BoilerPlateHooks::onNameOfHook"
	},
	"MessagesDirs": {
		"BoilerPlate": [
			"i18n"
		]
	},
	"ResourceModules": {
		"ext.boilerPlate.foo": {
			"scripts": [
				"resources/ext.boilerPlate.js",
				"resources/ext.boilerPlate.foo.js"
			],
			"styles": [
				"resources/ext.boilerPlate.foo.css"
			]
		}
	},
	"ResourceFileModulePaths": {
		"localBasePath": "",
		"remoteExtPath": "BoilerPlate"
	},
	"SpecialPages": {
		"HelloWorld": "SpecialHelloWorld"
	},
	"manifest_version": 2
}

注意:在wfLoadExtension( 'BoilerPlate' );執行後,全局變量$wgBoilerPlateEnableFoo不存在。 如果您給變量賦值(如在LocalSettings.php中),則來自extension.json的值將不會被使用。

關於在擴展中使用通用變量,請參考Manual:Configuration for developers

將class準備用於自動加載

如果您決定使用類/對象開發您的擴展,媒體維基提供了一個簡單的搜索類文件位置的方法。 在大多數情況下,這將免去開發自己的__autoload($classname)方法。

如想使用媒體維基的自動加載功能,您需要向AutoloadClasses 字段添加信息。 字段名稱為類名稱,內容為文件名。 對於一個簡單的單類文件擴展,類文件經常與擴展同名。所以您的自動加載部分內容可能是如下:

{
	"AutoloadClasses": {
		"MyExtension": "includes/MyExtension.php"
	}
}

文件名的路徑與extension.json文件所在目錄相對。

對於更複雜的擴展,應該要考慮到命名空間。 參見Manual:Extension.json/Schema#AutoloadNamespaces以獲取更多細節。

定義額外的鈎子

參見手冊:函數鉤

添加數據庫表格

Make sure the extension doesn't modify the core database tables. Instead, extension should create new tables with foreign keys to the relevant MW tables.

警告 警告: If your extension is used on any production WMF-hosted wiki please follow the Schema change guide.

If your extension needs to add its own database tables, use the LoadExtensionSchemaUpdates hook. See the manual page for more information on usage.

Set up localisation

參見:

添加日誌

On MediaWiki, all actions by users on wiki are tracked for transparency and collaboration. See Manual:Logging to Special:Log for how to do it.


Handling dependencies

Assume that an extension requires the presence of another extension, for example because functionalities or database tables are to be used and error messages are to be avoided in case of non-existence.

For example the extension CountingMarker requires the presence of the extension HitCounters for certain functions.

One way to specify this would be by using the requires key in extension.json.

Another option is using ExtensionRegistry (available since MW 1.25):

	if ( ExtensionRegistry::getInstance()->isLoaded( 'HitCounters', '>=1.1' ) {
		/* do some extra stuff, if extension HitCounters is present in version 1.1 and above */
	}

Currently (as of February 2024, MediaWiki 1.41.0) the name of the extension-to-be-checked needs to exactly match the name in their extension.json.[2][3]

Example: if you want to check the load status of extension "OpenIDConnect", you have to use it with a space

	if ( ExtensionRegistry::getInstance()->isLoaded( 'OpenID Connect' ) {
    ...
	}

本地化

While developing, you may want to disable both cache by setting $wgMainCacheType = CACHE_NONE and $wgCacheDirectory = false, otherwise your system message changes may not show up.

If you want your extension to be used on wikis that have a multi-lingual readership, you will need to add localisation support to your extension.

Store messages in <language-key>.json

Store message definitions in a localisation JSON file, one for each language key your extension is translated in. The messages are saved with a message key and the message itself using standard JSON format. Each message id should be lowercase and may not contain spaces. Each key should begin with the lowercased extension name. An example you can find in the MobileFrontend extension. Here is an example of a minimal JSON file (in this case en.json):

en.json

{
	"myextension-desc": "Adds the MyExtension great functionality.",
	"myextension-action-message": "This is a test message"
}

Store message documentation in qqq.json

The documentation for message keys can be stored in the JSON file for the pseudo language with code qqq. A documentation of the example above can be:

qqq.json:

{
	"myextension-desc": "The description of MyExtension used in Extension credits.",
	"myextension-action-message": "Adds 'message' after 'action' triggered by user."
}

Load the localisation file

In your extension.json, define the location of your messages files (e.g. in directory i18n/):

{
	"MessagesDirs": {
		"MyExtension": [
			"i18n"
		]
	}
}

Use wfMessage in PHP

In your setup and implementation code, replace each literal use of the message with a call to wfMessage( $msgID, $param1, $param2, ... ). In classes that implement IContextSource (as well as some others such as subclasses of SpecialPage), you can use $this->msg( $msgID, $param1, $param2, ... ) instead. Example:

wfMessage( 'myextension-addition', '1', '2', '3' )->parse()

Use mw.message in JavaScript

It's possible to use i18n functions in JavaScript too. Look at 手冊:Messages API for details.

擴充功能類型

Extensions can be categorized based on the programming techniques used to achieve their effect. Most complex extensions will use more than one of these techniques:

  • Subclassing: MediaWiki expects certain kinds of extensions to be implemented as subclasses of a MediaWiki-provided base class:
    • 特殊頁面 Subclasses of the SpecialPage class are used to build pages whose content is dynamically generated using a combination of the current system state, user input parameters, and database queries. Both reports and data entry forms can be generated. They are used for both reporting and administration purposes.
    • 外觀 Skins change the look and feel of MediaWiki by altering the code that outputs pages by subclassing the MediaWiki class SkinTemplate .
  • 函數鉤 A technique for injecting custom PHP code at key points within MediaWiki processing. They are widely used by MediaWiki's parser, its localization engine, its extension management system, and its page maintenance system.
    • Tag-function associations XML style tags that are associated with a php function that outputs HTML code. You do not need to limit yourself to formatting the text inside the tags. You don't even need to display it. Many tag extensions use the text as parameters that guide the generation of HTML that embeds Google objects, data entry forms, RSS feeds, excerpts from selected wiki articles.
  • 魔術字 A technique for mapping a variety of wiki text string to a single id that is associated with a function. Both variables and parser functions use this technique. All text mapped to that id will be replaced with the return value of the function. The mapping between the text strings and the id is stored in the array $magicWords. The interpretation of the id is a somewhat complex process – see 手冊:魔術字 for more information.
    • Variable Variables are something of a misnomer. They are bits of wikitext that look like templates but have no parameters and have been assigned hard-coded values. Standard wiki markup such as {{PAGENAME}} or {{SITENAME}} are examples of variables. They get their name from the source of their value: a php variable or something that could be assigned to a variable, e.g. a string, a number, an expression, or a function return value.
    • 解析器函數 {{functionname: argument 1 | argument 2 | argument 3...}}. Similar to tag extensions, parser functions process arguments and returns a value. Unlike tag extensions, the result of parser functions is wikitext.
  • API模塊 You can add custom modules to MediaWiki's action API, that can be invoked by JavaScript, bots or third-party clients.
  • 頁面內容模型 If you need to store data in formats other than wikitext, JSON, etc. then you can create a new ContentHandler .

Support other core versions

There are two widespread conventions for supporting older versions of MediaWiki core:

  • Master: the master branch of the extension is compatible with as many old versions of core as possible. This results in a maintenance burden (backwards-compatibility hacks need to be kept around for a long time, and changes to the extension need to be tested with several versions of MediaWiki), but sites running old MediaWiki versions benefit from functionality recently added to the extension.
  • Release branches: release branches of the extension are compatible with matching branches of core, e.g. sites using MediaWiki 1.42 need to use the REL1_42 branch of the extension. (For extensions hosted on Gerrit, these branches are automatically created when new versions of MediaWiki are released.) This results in cleaner code and faster development but users on old core versions do not benefit from bugfixes and new features unless they are backported manually.

Extension maintainers should declare with the compatibility policy parameter of the {{Extension/zh }} template which convention they follow.

許可協議

MediaWiki is an open-source project and users are encouraged to make any MediaWiki extensions under an Open Source Initiative (OSI) approved license compatible with GPL-2.0-or-later (Wikimedia's standard software license).

We recommend adopting one of the following compatible licenses for your projects in Gerrit:

For extensions that have a compatible license, you can request developer access to the MediaWiki source repositories for extensions. To specify the licence in code and with "license-name" a key should be used to provide it's short name, e.g. "GPL-2.0-or-later" or "MIT" adhering to the list of identifiers at spdx.org.


發布

To autocategorize and standardize the documentation of your existing extension, please see 模板:Extension/zh . To add your new extension to this Wiki:

A developer sharing their code in the MediaWiki code repository should expect:

Feedback / Criticism / Code reviews
Review and comments by other developers on things like framework use, security, efficiency and usability.
Developer tweaking
Other developers modifying your submission to improve or clean-up your code to meet new framework classes and methods, coding conventions and translations.
Improved access for wiki sysadmins
If you do decide to put your code on the wiki, another developer may decide to move it to the MediaWiki code repository for easier maintenance. You may then create a 開發者賬戶 to continue maintaining it.
Future versions by other developers
New branches of your code being created automatically as new versions of MediaWiki are released. You should backport to these branches if you want to support older versions.
Incorporation of your code into other extensions with duplicate or similar purposes — incorporating the best features from each extension.
Credit
Credit for your work being preserved in future versions — including any merged extensions.
Similarly, you should credit the developers of any extensions whose code you borrow from — especially when performing a merger.

Any developer who is uncomfortable with any of these actions occurring should not host in the code repository. You are still encouraged to create a summary page for your extension on the wiki to let people know about the extension, and where to download it.

Deploying and registering

If you intend to have your extension deployed on Wikimedia sites (including possibly Wikipedia), additional scrutiny is warranted in terms of performance and security. Consult 編寫一個部署用的擴充功能 .

If your extension adds namespaces, you may wish to register its default namespaces; likewise, if it adds database tables or fields, you may want to register those at 數據庫字段前綴 .

Please be aware that review and deployment of new extensions on Wikimedia sites can be extremely slow, and in some cases has taken more than two years.[4]

Help documentation

You should provide public domain help documentation for features provided by your extension. 說明:CirrusSearch is a good example. You should give users a link to the documentation via the addHelpLink() function.

Providing support / collaboration

Extension developers should open an account on Wikimedia's Phabricator , and request a new project for the extension. This provides a public venue where users can submit issues and suggestions, and you can collaborate with users and other developers to triage bugs and plan features of your extension.

參見

Learn by example

    • Allows you to get going quickly with your own extension.


參考資料