Manual:Variable
From MediaWiki.org
- This page is about creating variables. For help using default variables, see Help:Variables.
| Tag Extensions | Parser Functions | Hooks | Special Pages | Skins | Magic Words |
Variables 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. You can also extend wiki markup by defining your own custom variables.
The term is something of a misnomer because there is nothing variable about a variable. End users cannot change the value of a variable because it is predetermined by a bundle of php code that calculates its value. The term "variables" comes 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.
Contents |
[edit] Defining custom variables
Variables are a special case of magic words so our first step will be to define the variable as a magic word:
- Choose a magic word id for your variable. This is only an internal identifier that is used to tie together the various parts of the variable definition: the names that appear in wiki text, and the php code that assigns a value to the variable. It is best to choose an id that will be uniquely associated with your extension and is unlikely to be confused with other magic word ids used by other extensions. A common strategy is to use something like
MAG_canonicalnamewhere canonicalname is the name under which you will register your extension (see Registering custom variables below). - Define the names that will appear in wiki text. To accomplish this, you will need to define and register a hook function with LanguageGetMagic. Your hook function will be passed an array and the hook function will add an entry whose key is the internal magic word id and whose value is an array containing all the names you want to use for your variable. Your names can be case sensitive and language dependent. See LanguageGetMagic and magic words for more information.
- Provide php code to assign a value to the variable. To accomplish this, you will need to define and register a hook function with Manual:Hooks/ParserGetVariableValueSwitch.
Note that the only difference between this process and the general process for defining magic words is the last step: defining a hook function for Manual:Hooks/ParserGetVariableValueSwitch. Parser functions have a different method for associating an id with php code. See Manual:Parser functions for more information.
[edit] Registering custom variables
This is a two step process:
- Define the variable so that it gets included in
Special:Versions. This requires adding a member to $wgExtensionCredits. For more information, please see Registering features with MediaWiki. - Declare the magic word id as a variable. To accomplish this we write and assign a hook to
MagicWordwgVariableIDs, the subject of this article. Note: this hook is only for use with variables. Do not use it to define parser functions.
[edit] Example
Note: if you wish to use this example as a coding template, please replace 'My' with something unique to your project so that there is less risk of name clashes with MediaWiki or any of its extensions. For example, if your extension was named BigExtravagantStylingTool and you were reasonably sure that no-one else had an extension with constants, variables, functions, or classes beginning 'BEST_', 'wgBEST', 'wfBEST', or even 'BEST' you might want to replace 'My' with 'BEST'.
#-------------------------------------------------- # Step 1: choose a magic word id #-------------------------------------------------- # storing the chosen id in a constant is not required # but still good programming practice - it makes # searching for all occurrences of the magic word id a # bit easier - note that the the name of the constant # and the value it is assigned don't have to have anthing # to do with each other. define('MAG_NIFTYVAR', 'mycustomvar1'); #--------------------------------------------------- # Step 2: define some words to use in wiki markup #--------------------------------------------------- $wgHooks['LanguageGetMagic'][] = 'wfMyWikiWords'; function wfMyWikiWords(&$aWikiWords, &$langID) { #tell MediaWiki that all {{NiftyVar}}, {{NIFTYVAR}}, #{{CoolVar}}, {{COOLVAR}} and all case variants found #in wiki text should be mapped to magic id 'mycustomvar1' # (0 means case-insensitive) $aWikiWords[MAG_NIFTYVAR] = array(0, 'NiftyVar','CoolVar'); #must do this or you will silence every LanguageGetMagic #hook after this! return true; } #--------------------------------------------------- # Step 3: assign a value to our variable #--------------------------------------------------- $wgHooks['ParserGetVariableValueSwitch'][] = 'wfMyAssignAValue'; function wfMyAssignAValue(&$parser, &$cache, &$magicWordId, &$ret) { if (MAG_NIFTYVAR == $magicWordId) { // We found a value $ret='This is a really silly value'; } // We must return true for two separate reasons: // 1. To permit further callbacks to run for this hook. // They might override our value but that's life. // Returning false would prevent these future callbacks from running. // 2. At the same time, "true" indicates we found a value. // Returning false would the set variable value to null. // // In other words, true means "we found a value AND other // callbacks will run," and false means "we didn't find a value // AND abort future callbacks." It's a shame these two meanings // are mixed in the same return value. So as a rule, return // true whether we found a value or not. return true; } #--------------------------------------------------- # Step 4: register the custom variables so that it # shows up in Special:Version under the # listing of custom variables #--------------------------------------------------- $wgExtensionCredits['variable'][] = array( 'name' => 'NiftyVar', 'author' =>'John Doe', 'url' => 'http://www.mediawiki.org/wiki/Extension:NiftyVar', 'description' => 'This variable is an example and performs no discernable function' ); #--------------------------------------------------- # Step 5: register wiki markup words associated with # MAG_NIFTYVAR as a variable and not some # other type of magic word #--------------------------------------------------- $wgHooks['MagicWordwgVariableIDs'][] = 'wfMyDeclareVarIds'; function wfMyDeclareVarIds(&$aCustomVariableIds) { #aCustomVariableIds is where MediaWiki wants to store its #list of custom variable ids. We oblige by adding ours: $aCustomVariableIds[] = MAG_NIFTYVAR; #must do this or you will silence every MagicWordwgVariableIds #registered after this! return true; }
[edit] Extensions with multiple variables
You may, of course, define more than one variable for an extension. Repeating the above code for each variable may be a bit tedious. Below is a method that lets you define a data structure with all the data about all the variables in one place. The code following uses that data to set up the registration.
Separating code and data in this fashion has several advantages:
- everything is in one place if you need to change it
- its easy to get a quick overview of all your extension's variables
The main disadvantage is that the code is a bit abstract and may be hard for a new php programmer to understand.
Note: the code below is presented for concept purposes only: it has not been tested for syntax errors - use as a template at your own risk.
#-------------------------------------------------- # Step 1: define a data structure storing information # for each variable variable in your extension. This # structure has four elements: # [0] = canonical name # [1] = description # [2] = an array of wiki text for the variable, keyed by language # [3] = a code snippet that sets the value of the variable. There # is no limit on the code complexity - any bit of code that # can go on the right side of an equal sign is OK. The # snippet should end with a ';'. Also, don't forget that # wherever the actual code should have a backslash, the code # snippet should have a double backslash - you loose one of # the backslashes when php converts your quoted string into # an actual string. i.e. '\\n' is equivalent to coding \n # # The code below sets up two variables, one which is equal to the # string: 'This is a really silly value' and the other # will be set to 42. #-------------------------------------------------- $wgMyExtensionVariables = array( array('NiftyVar1' , 'One of the variables in my extension' , array( 'en' => array(0, 'NiftyVar1') , 'fr' => array(0, 'NiftyVar1', 'VarChouette1')) ) , '\'This is a really silly value\';' ) , array('NiftyVar2' , 'The other variable in my extension' , array( 'en' => array(0, 'NiftyVar2') , 'fr' => array(0, 'NiftyVar1', 'VarChouette2') ) , '42;' ) ) ); #--------------------------------------------------- # Step 2: attach a function that sets up the mapping # between each variable and its wiki words. # # The function is defined below in step 4. #--------------------------------------------------- $wfHooks['LanguageGetMagic'] = 'wfMyWikiWords'; #---------------------------------------------------- # Step 3: For each variable, set up the association # between the magic word id and the php code # that assigns it a value. Also register # each variable. # # The function that does the work is defined below # in step 4. This is OK because in php4 and 5 you # can place code that uses a function *before* its # actual definition. #---------------------------------------------------- $wgMyExtensionAuthor = 'John Doe'; $wgMyExtensionURL = 'http://www.mediawiki.org/wiki/Extension:NiftyVars' wfMyExtensionDefineAndRegisterVariables($wgMyExtensionAuthor , $wgMyExtensionURL , $wgMyExtensionVariables); #--------------------------------------------------- # Step 4: define the functions we referenced in # steps 2 and 3. # # These are grouped together because this # code is not specific to any particular # extension. These functions will work with # any array defined like the array in step 4. #--------------------------------------------------- # --------------------------------------------------- # Step 4a: define the function used for the # 'LanguageGetMagic' hook # --------------------------------------------------- function wfMyWikiWords(&$aWikiWords, &$langID) { foreach ($wgMyExtensionVariables as $aVariableData) { $sCanonicalName =& $aVariableData[0]; $aAllLanguages =& $aVariableData[2]; #use a language specific array if available #otherwise default to english $sMagicWordId = 'MAG_' . $sCanonicalName; if (isset($aAllLanguages[$langID])) { $aText =& $aAllLangauges[$langID]; } else { $aText =& $aAllLangauges['en']; } $aWikiWords[$sCanonicalName, $aText]; } return true; } #--------------------------------------------------- # Step 4b: Create a function that walks through an # array of variable definitions like the one # we defined in step 1 and sets up the # magic word id association with php code # and registers the variable # # The function below takes three arguments # so that is is completely independent of # whatever naming convention we chose for # our global variables. #--------------------------------------------------- function wfMyExtensionDefineAndRegisterVariables(&$aVariables , $sAuthor , $sURL) { $sAssignAValue = 'switch($magicWordId){' $sRegisterVariables=''; foreach($aVariables as $aVariableData) { $sCanonicalName = $aVariableData[0]; $sDescription = $aVariableData[1]; $sAssignmentCode = $aVariableData[3]; #associate the magic word id with a value $sMagicWordId = '\'MAG_' . $sCanonicalName . '\''; $sAssignAValue .= 'case ' . $sMagicWordId . ': $ret=' . $sCode . '; return true;' #publish via Special:Version $wgExtensionCredits['variable'][] = array( 'name' => $sCanonicalName, 'author' => $sAuthor, 'url' => $sURL, 'description' => $sDescription ); #add code to register variable $sAssignAValue .= 'default: return true; }'; $sRegisterVariables .= '$aCustomVariableIds[] =' . $sMagicWordId . ';'; } #complete and attach the php code to the magic word id $wgHooks['ParserGetVariableValueSwitch'][] = create_function('&$parser, &$cache, &$magicWordId, &$ret' , $sAssignAValue); #complete and attach the variable registration hook $sRegisterVariables .= 'return true;'; $wgHooks['MagicWordwgVariableIDs'][] = create_function('&$aCustomVariableIds' , $sRegisterVariables); }
The code above is just one approach to the problem of multiple variables. For an alternative approach to group definition and registration, see Extension:Variables.
[edit] For more information
- Help:Variables - discusses default variables built into the core MediaWiki package
- Manual:Magic words - reviews the different kinds of magic words and how MediaWiki tells apart variables, parser functions, and templates.

