Jump to content

Manual:Message.php

From mediawiki.org
This page is a translated version of the page Manual:Message.php and the translation is 50% complete.

MW 1.41 and earlier:

The Message class deals with fetching and processing of interface message into a variety of formats. It is intended to replace the old wfMsg* functions that over time grew unusable. See Manual:Messages API for equivalences between old and new functions.

Usage

The preferred way to create Message objects is via the msg() method of an available RequestContext and ResourceLoader Context object; this will ensure that the message uses the correct language. When that is not possible, the wfMessage() global function can be used, which will cause Message to get the language from the global RequestContext object. In rare circumstances when sessions are not available or not initialized, that can lead to errors.

The most basic usage cases would be:

// Initialize a Message object using the 'some_key' message key
$message = $context->msg( 'some_key' );

// Using two parameters those values are strings 'value1' and 'value2':
$message = $context->msg( 'some_key',
    'value1', 'value2'
);

Global function wrapper

Since msg() returns a Message instance, you can chain its call with a method. Some of them return a Message instance too so you can chain them. You will find below several examples of msg() usage.

Fetching a message text for interface message:

$button = Xml::button(
    $context->msg( 'submit' )->text()
);

A Message instance can be passed parameters after it has been constructed, use the params() method to do so:

$context->msg( 'welcome-to' )
        ->params( $wgSitename )
        ->text();

{GRAMMAR}} and friends work correctly:

$context->msg( 'are-friends',
     $user, $friend
);
$context->msg( 'bad-message' )
        ->rawParams( '<script>...</script>' )
        ->escaped();

Changing language

Messages can be requested in a different language or in whatever current content language is being used. The methods are:

  • Message->inContentLanguage()
  • Message->inLanguage()

Sometimes the message text ends up in the database, so content language is needed:

wfMessage( 'file-log',
     $user, $filename
)->inContentLanguage()->text();

Checking whether a message exists:

$context->msg( 'mysterious-message' )->exists()
// returns a boolean whether the 'mysterious-message' key exist.

If you want to use a different language:

$userLanguage = $user->getOption( 'language' );
wfMessage( 'email-header' )
      ->inLanguage( $userLanguage )
      ->plain();

You can parse the text only in the content or interface languages.

See also