Manual:Coding conventions

This page describes the coding conventions used within the MediaWiki codebase and extensions which are intended for use on Wikimedia websites, including appropriate naming conventions. If you would like a short checklist to help you review your commits, try using the pre-commit checklist.

All languages
Some general guidelines apply to all MediaWiki code, whatever language it is written in.

Tab size
Lines should be indented with a single tab character per indenting level. You should make no assumptions about the number of spaces per tab. Most MediaWiki developers find 4 spaces per tab to be best for readability, but many systems are configured to use 8 spaces per tab and some developers might use 2 spaces per tab.

Newlines
All text files should be checked in to Subversion with svn:eol-style set to "native". This is necessary to prevent corruption by certain Windows-based text editors.

You can ask subversion to automatically set this property on a given list of file type. This is done with subversion auto-props and will save you the hassle to manually set the property when adding new files.

You might want to read the English Wikipedia article about newline.

Encoding
All text files MUST be encoded with UTF-8 without Byte Order Marks.

Do not use Microsoft Notepad to edit files. Notepad always inserts BOM. BOM will stop PHP files from working since it is a special character inserted at the very top of the file and will be outputted by the web browser to the client.

In short, make sure your editor supports UTF-8 without BOM.

General style
MediaWiki's indenting style is similar to the so-called "One True Brace Style". Braces are placed on the same line as the start of the function, conditional, loop, etc.

Multi-line statements are written with the second and subsequent lines being indented by one extra level:

Use indenting and line breaks to clarify the logical structure of your code. Expressions which nest multiple levels of parentheses or similar structures may begin a new indenting level with each nesting level:

There are some exceptions, such as switch statements, where the indentation of the cases are optional, so both of the below are fine.

Vertical alignment
Avoid vertical alignment. It tends to create diffs which are hard to interpret, since the width allowed for the left column constantly has to be increased as more items are added.

When needed, create mid-line vertical alignment with spaces. For instance this:

Is achieved as follows with spaces rendered as dots:

$namespaceNames·=·array(  →    NS_MEDIA············=>·'Media',   →    NS_SPECIAL··········=>·'Special',   →    NS_MAIN·············=>·'',

Line continuation
Lines should be broken at between 80 and 100 columns. There are some rare exceptions to this. Functions which take lots of parameters are not exceptions.

The operator separating the two lines may be placed on either the following line or the preceding line. An operator placed on the following line is more visible and so is more often used when the author wants to draw attention to it:

An operator placed on the preceding line is less visible, and is used for more common types of continuation such as concatenation and comma:

When continuing "if" statements, a switch to Allman-style braces makes the separation between the condition and the body clear:

Opinions differ on the amount of indentation that should be used for the conditional part. Using an amount of indentation different to that used by the body makes it more clear that the conditional part is not the body, but this is not universally observed.

Continuation of conditionals and very long expressions tend to be ugly whichever way you do them. So it's sometimes best to break them up by means of temporary variables.

Spaces
MediaWiki favours a heavily-spaced style for optimum readability.

Put spaces on either side of binary operators, for example:

not like this:

Put spaces next to parentheses on the inside, except where the parentheses are empty. Do not put a space following a function name.

Opinions differ as to whether control structures, , and  should be followed by a space; the following two styles are acceptable:

Single-line comments should have a space between the or  and the comment text.

To help developers fix code with an inadequately spacey style, a tool called stylize.php has been created, which uses PHP's tokenizer extension to add spaces at the relevant places.

Braceless control structures
Do not use single-line statements:

They reduce the readability of the code by moving important statements away from the left margin, where the reader is looking for them. Remember that making code shorter doesn't make it simpler. The goal of coding style is to communicate effectively with humans, not to fit computer-readable text into a small space.

Most MediaWiki developers favour fully-braced control structures:

This avoids a common logic error, which is especially prevalent when the developer is using a text editor which does not have a "smart indenting" feature. The error occurs when a single-line block is later extended to two lines:

Later changed to:

This has the potential to create subtle bugs.

emacs style
In emacs, using php-mode.el from nXHTML mode, you can set up a MediaWiki minor mode in your .emacs file:

The above mah/sniff-php-style function will check your path when php-mode is invoked to see if it contains “mw” or “mediawiki” and set the buffer to use the mw-mode minor mode for editing MediaWiki source. You will know that the buffer is using mw-mode because you'll see something like “PHP MW” or “PHP/lw MW” in the mode line.

File naming
Files which contain server-side code should be named in UpperCamelCase. Name the file after the most important class it contains; most files will contain only one class, or a base class and a number of descendants. For instance, Title.php contains only the Title class; HTMLForm.php contains the base class HTMLForm, but also the related class HTMLFormField</tt> and its descendants.

Name 'access point' files, such as JavaScript, CSS, images, SQL, and PHP entry points such as index.php</tt> and load.php</tt>, in lowercase</tt>. Maintenance scripts are generally in lowerCamelCase</tt>, although this varies somewhat. Files intended for the site administrator, such as readmes, licenses and changelogs, are usually in UPPERCASE</tt>.

Never include spaces in filenames or directories, or use non-ASCII characters. For lowercase titles, hyphens are preferred to underscores.

For JS and CSS files loaded via ResourceLoader, naming should generally match up with the RL module naming:


 * module mediawiki.util
 * resources/mediawiki.util/mediawiki.util.js
 * resources/mediawiki.util/mediawiki.util.jpegmeta.js
 * resources/mediawiki.util/mediawiki.util.test.js

JS and CSS files for extensions usually should use a name like ext.myextname, for instance:
 * extensions/SVGEdit/resources/ext.svgedit.embedapi.js

This keeps it easy to find things, even if you divide up a module into smaller files for editing convenience and then bundle them together into a single module.

Assignment expressions
Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:

Space is cheap, and you're a fast typist, so instead use:

Using assignment in a clause used to be legitimate, for iteration:

This is unnecessary in new code; instead use:

Ternary operator
The ternary operator can be used profitably if the expressions are very short and obvious:

But if you're considering a multi-line expression with a ternary operator, please consider using an block instead. Remember, disk space is cheap, code readability is everything, "if" is English and ?: is not.

5.3 shorthand
Since we still support PHP 5.2.x, use of the shorthand ternary operator introduced in PHP 5.3 is not allowed.

String literals
For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Perhaps more importantly, they are easier to type, since you don't have to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.

However, do not be afraid of using PHP's double-quoted string interpolation feature: This has slightly better performance characteristics than the equivalent using the concatenation (dot) operator, and it looks nicer too.

Heredoc-style strings are sometimes useful:

Some authors like to use END as the ending token, which is also the name of a PHP function. This leads to IRC conversations like the following:

<Simetrical>	vim also has ridiculously good syntax highlighting. <TimStarling>	it breaks when you write <<<END in PHP <Simetrical>	TimStarling, but if you write <<<HTML it syntax-highlights as HTML! <TimStarling>	I have to keep changing it to ENDS so it looks like a string again <brion-codereview>	fix the bug in vim then! <TimStarling>	brion-codereview: have you ever edited a vim syntax script file? <brion-codereview>	hehehe <TimStarling>	http://tstarling.com/stuff/php.vim <TimStarling>	that's half of it... <TimStarling>	here's the other half: http://tstarling.com/stuff/php-syntax.vim <TimStarling>	1300 lines of sparsely-commented code in a vim-specific language <TimStarling>	which turns out to depend for its operation on all kinds of subtle inter-pass effects TimStarling: it looks like some franken-basic language.

Functions and parameters
Avoid passing huge numbers of parameters to functions or constructors: It quickly becomes impossible to remember the order of parameters, and you will inevitably end up having to hardcode all the defaults in callers just to customise a parameter at the end of the list. If you are tempted to code a function like this, consider passing an associative array of named parameters instead.

In general, using boolean parameters is discouraged in functions. In, without looking up the documentation for , it is impossible to know what those parameters are meant to indicate. Much better is to either use class constants, and make a generic flag parameter: Or to make your function accept an array of named parameters:

Try not to repurpose variables over the course of a function, and avoid modifying the parameters passed to a function (unless they're passed by reference and that's the whole point of the function, obviously).

C borrowings
The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.

In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.

PHP has three special literals:, and. Homesick C developers write as  because they want to believe that it is a macro defined as. This is not necessary.

Use not. They have subtly different meanings: And the latter has poorer performance.

PHP pitfalls

 * Understand and read the documentation for isset</tt> and empty</tt>. Use them only when appropriate.
 * is inverted conversion to boolean with error suppression. Only use it when you really want to suppress errors. Otherwise just use . Do not use it to test if an array is empty, unless you simultaneously want to check if the variable is unset.
 * Do not use to test for .  Using  in this situation could introduce errors by hiding mis-spelled variable names.  Instead, use
 * Study the rules for conversion to boolean. Be careful when converting strings to boolean.
 * Be careful with double-equals comparison operators. Triple-equals is often more intuitive.
 * is true
 * is true
 * is false
 * Array plus does not renumber the keys of numerically-indexed arrays, so . If you want keys to be renumbered, use array_merge:
 * Make sure you have error_reporting</tt> set to for PHP 5.  This will notify you of undefined variables and other subtle gotchas that stock PHP will ignore. See also Manual:How to debug.
 * When working in a pure PHP environment, remove any trailing  tags. These tags often cause issues with trailing white-space and "headers already sent" error messages (cf. 17642 and <http://news.php.net/php.general/280796>).

Integration
There are a few pieces of code in the MediaWiki codebase which are intended to be standalone and easily portable to other applications; examples include the UTF normalisation in /includes/normal</tt> and the libraries in /includes/libs</tt>. Apart from these, code should be integrated into the rest of the MediaWiki environment, and should allow other areas of the codebase to integrate with it in return.

Global objects
Do not access the PHP superglobals, , etc, directly; use instead; there are various functions depending on what type of value you want. Equally, do not access directly; use  if you want to get the IP address of the current user.

Classes
Encapsulate your code in an object-oriented class, or add functionality to existing classes; do not add new global functions or variables. Try to be mindful of the distinction between 'backend' classes, which represent entities in the database (eg User</tt>, Block</tt>, Revision</tt>, etc), and 'frontend' classes, which represent pages or interfaces visible to the user (SpecialPage</tt>, Article</tt>, <tt>ChangesList</tt>, etc. Even if your code is not obviously object-oriented, you can put it in a static class (eg <tt>IP<tt> or <tt>Html</tt>).

As a holdover from PHP 4's lack of private class members and methods, older code will be marked with comments such as to indicate the intention; respect this as if it were enforced by the interpreter.

Mark new code with proper visibility modifiers, including if appropriate, but do not add visibility to existing code without first checking, testing and refactoring as required. It's generally a good idea to avoid visibility changes unless you're making changes to the function which would break old uses of it anyway.

Error handling
Don't suppress errors with PHP's @ operator, for any reason ever. It's broken when E_STRICT is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support. Use  and   instead.

Naming
Use lowerCamelCase when naming functions or variables. For example:  Use UpperCamelCase when naming classes:. Use uppercase with underscores for global and class constants:,. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.

There are also some prefixes used in different places:

Functions

 * <tt>wf</tt> (wiki functions) - Top-level functions, e.g.

Verb phrases are preferred: use instead of.

Variables

 * <tt>$wg</tt> - global variables, e.g., . Always use this for new globals, so that it's easy to spot missing "global $wgFoo" declarations. In extensions, the extension name should be used as a namespace delimiter. For example, , not $wgConditionLimit.

It is common to work with an instance of the <tt>Database</tt> class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. This is of particular importance in replicated environments, such as Wikimedia and other large wikis; in development environments there is usually no difference between the two types, which can conceal subtle errors.


 * - a Database object for writing (a master connection)
 * - a Database object for non-concurrency-sensitive reading (this may be a read-only slave, slightly behind master state, so don't ever try to write to the database with it, or get an 'authoritative' answer to important queries like permissions and block status)

The following may be seen in old code but are discouraged in new code:


 * <tt>$ws</tt> - Session variables, e.g.
 * <tt>$wc</tt> - Cookie variables, e.g.
 * <tt>$wp</tt> - Post variables (submitted via form fields), e.g.
 * <tt>$m</tt> - object member variables: . This is discouraged in new code, but try to stay consistent within a class.

Inline
The Doxygen documentation style is used (it is very similar to PHPDoc for the subset that we use). A code documentation example: giving a description of a function or method, the parameters it takes (using <tt>@param</tt>), and what the function returns (using <tt>@return</tt>), or the <tt>@ingroup</tt> or <tt>@author</tt> tags.

Use "@" rather than "\" as the escape character (e.g. use <tt>@param<tt> rather than <tt>\param</tt>) - both styles work in Doxygen, but the <tt>@param<tt> style works with PHPDoc too, whereas the <tt>\param</tt> style does not. Use "/**" to begin the comments, instead of the Qt-style formating "/*!".

General format for parameters is such: <tt>@param $varname [type] [description]</tt> (see the note in ):

PHPDoc was used at the very beginning but got replaced with Doxygen for performance reason. We should probably drop PHPDoc compatibility.

There are a number of bugs in Doxygen that affect MediaWiki's documentation:
 * Bug 613185 - PHP datatype in de @param
 * Doxygen should recognise both <tt>@param $varname [type] [description]</tt> and <tt>@param [type] $varname [description]</tt> but for now only the former works. Until this bug is fixed, make sure you don't put <tt>[type]</tt> before <tt>$varname</tt>.
 * Bug 626105 - @var in php is not documented
 * <tt>@var</tt> should be usable to document class members' type, but doesn't work for now.

<tt>/docs</tt> folder
Some elements of MediaWiki are documented in the /docs folder. For instance, if you add a new hook, you should update docs/hooks.txt with the name of the hook, a description of what the hook does, and the parameters used by the hook.

Release notes
All significant changes to the core software which might affect wiki users, server administrators, or extension authors, must be documented in the <tt>RELEASE-NOTES</tt> file. This file is refreshed on every release (with the past content going into <tt>HISTORY</tt>) and is generally divided into three sections:


 * Configuration changes is the place to put changes to accepted default behaviour, backwards-incompatible changes, or other things which need a server administrator to look at and decide "is this change right for my wiki?". Try to include a (brief!) explanation of how the previous functionality can be recovered if desired.
 * Bug fixes is the place to note changes which fix behaviour which is accepted to be problematic or undesirable. These will often be issues reported in bugzilla, but needn't necessarily.
 * New features is, unsurprisingly, to note the addition of new functionality.

In all cases, if your change is in response to an issue reported in bugzilla, include the bug reference at the start of the entry. New entries are added in chronological order at the end of the section.

Messages
When creating a new message, use hyphens (-) where possible instead of CamelCase or rails_underscored_variables. So for example, "some-new-message" is a good name, while "someNewMessage" and "some_new_message" are not.

If the message is going to be used as a label which can have a colon after it, don't hardcode the colon; instead, put the colon inside the message text. Some languages (such as French which require a space before) need to handle colons in a different way, which is impossible if the colon is hardcoded.

HTML class and ID names should be prefixed with "mw-". It seems most common to hyphenate them after that, like "mw-some-new-class". Using the "mw-" prefix avoids conflicts with IDs generated by the wikitext parser to mark section headings.

Try to use message keys 'whole' in code, rather than building them on the fly; as this makes it easier to search for them in the codebase. For instance, Is bad because a search for <tt>templatesused-section</tt> will not find this use of the message key. Instead do:

MySQL
Use <tt>UPPERCASE</tt> for MySQL keywords, and lowercase for things like types. Do not specify the lengths of numeric types, but do for and  types. Use for all timestamps, and parse them to the standard format using ; do not use the  field type.

Make sure to include the comment immediately before any table name; this will be replaced with the wiki's database prefix if necessary, and ommitting it will cause breakage. Similarly, include the comment after any table declaration, and  immediately before any index names.

Create indices as separate statements, do not include them in the table creation query; the separate syntax is clearer and makes it easier to see the difference between unique and non-unique indices.

Table naming

 * Table names should be singular nouns: <tt>user</tt>, <tt>page</tt>, <tt>revision</tt>, etc. There are some historical exceptions: <tt>pagelinks</tt>, <tt>categorylinks</tt>...
 * Column names are given a prefix derived from the table name: the name itself if it's short, or an abbreviation:
 * <tt>page</tt> &rarr; <tt>page_id</tt>, <tt>page_namespace</tt>, <tt>page_title</tt>...
 * <tt>categorylinks</tt> &rarr; <tt>cl_from</tt>, <tt>cl_namespace</tt>...

JavaScript
In most cases conventions for PHP can perfectly apply to JavaScript. Such as whitespace (see ). function myFunction( lorem, ipsum ) { → var → myVar = 'foo', →    →  someOther = 'thing', →    →  loremArr = [], →    →  concatString = myVar + ': ' + someOther;
 * Document functions and variables (see ). Make sure though that you use the JavaScript term (ie. not  but  )
 * Use tabs for indention at the begin of a line instead of spaces.
 * Keep parentheses around arguments connected to the function name( , seperate everything with a single space.
 * Always define variables with a clear statement on whether they are local or global ( or  ). Especially since ResourceLoader combines several scripts into 1 file wrapped in a self-executing anonymous function you can't make an assumption over its scope and imply whether it is local or not. Make it clear.
 * Use array and object literal notation
 * Don't use multiple  statements, combine them when possible and indent with a tab:

/* function body here */ }
 * Don't apply styling to lots of elements at once; this has poor performance. Instead use a common parent's class (or add one) and apply CSS in a .css file. Unless loaded separately or without ResourceLoader, this will all be loaded in the same HTTP request, so there's no performance penalty. Do not write CSS inline in JS files.
 * Be careful with compatibility with left-to-right and right-to-left languages (ie. "float:right" or "text-align:left"), especially when styling text containers.
 * Use dot-notation whenever possible to access object members. ( instead of  )
 * Validate with JSHint as much as possible. Recommended JSHint settings: [x] Require curly braces around all blocks; [x] Don't check line breaks; [x] Browser

jQuery
jQuery is now provided as a standard library in MediaWiki 1.17; familiarize yourself with its API and don't be afraid to use jQuery for DOM manipulation, AJAX hits, and utility functions. These are usually much easier to work with than classic low-level DOM and DHTML interfaces, and much more consistent across browsers.


 * (jqbug 8229) Attribute selector values should always be quoted. Will not fail in simple cases or in jQuery versions older than 1.5, but as good practice, always quote attribute values in the selector:


 * Start variable names that are an instance of jQuery with a dollar sign to avoid confusion with raw elements.

By naming them like  it's clear what they are even if there's many lines of code in between:


 * Checking for Arrays or Functions should be done through $.isArray and $.isFunction at all times to cover for edge cases and cross-browser differences.
 * Do not assume the existence of any global variables other than  and  . For example <tt>$</tt> should always be aliased locally
 * Always wrap your code in a closure or scope which defines it. This avoids leaking variables to or being given local variables from, another module. Use one of the following structures ("Immediately-Invoked Function Expression" ) to wrap code:

JS pitfalls

 * Undeclared variables are assumed to be global -- the opposite of PHP. Declare all your local variables with <tt>var</tt>!
 * Numbers can be coerced to strings, but strings never implicitly turn into numbers as they do in PHP -- you may need to use parseInt or parseFloat explicitly at times.
 * JavaScript concatenates strings with <tt>+</tt> not <tt>.</tt> -- you will get unexpected results when you mix these up. :)
 * 'Single-quoted strings' in JavaScript are escaped the same way as "double-quoted strings", unlike PHP where they have different rules.
 * When throwing exceptions, use <tt>throw new Error('message')</tt> rather than <tt>throw 'message'</tt>. You can throw a string directly in JavaScript, but some debuggers won't pick up a stack trace or the location of the error without using the <tt>Error</tt> class.
 * See ResourceLoader/Developing with ResourceLoader for how to switch into debug mode; by default in MediaWiki 1.17 and higher most JS files will be combined and minified to reduce load time, but original source is easier to work with in your browser's debugger.

Commenting and documentation
In older versions of MediaWiki, JavaScript code was often very poorly commented to keep it small. Since MediaWiki 1.17 and higher run code through ResourceLoader's minification helpers by default, please feel free to liberally comment your code to aid future maintainers.

Doxygen/jsdoc documentation is not yet built automatically from JavaScript files, but it may be at some point in the future. In the meantime, some advanced editors like NetBeans can make use of jsdoc-style annotations to aid in autocomplete and code navigation.

Here's a nice example from the mediawiki.util module:

CSS

 * One selector per line
 * Opening braces on the same line
 * Indent each property with 1 tab
 * 1 space seperation between property colon and value
 * a semi-colon after each property (also after the last one)
 * Closing braces unindented back to the left

To do

 * Function parameter choice
 * Expand the CSS and JS sections