Internationalization

Internationalization (I18N) refers to the process of designing a softwareapplication so that it can be adapted to various languages and regionswithout engineering changes. For Web applications, this is of particularimportance because the potential users may be from worldwide.

Yii provides support for I18N in several aspects.

  • It provides the locale data for each possible language and variant.
  • It provides message and file translation service.
  • It provides locale-dependent date and time formatting.
  • It provides locale-dependent number formatting.
    In the following subsections, we will elaborate each of the above aspects.

1. Locale and Language

Locale is a set of parameters that defines the user's language, countryand any special variant preferences that the user wants to see in theiruser interface. It is usually identified by an ID consisting of a languageID and a region ID. For example, the ID en_US stands for the locale ofEnglish and United States. For consistency, all locale IDs in Yii arecanonicalized to the format of LanguageID or LanguageID_RegionIDin lower case (e.g. en, en_us).

Locale data is represented as a CLocale instance. It provideslocale-dependent information, including currency symbols, number symbols,currency formats, number formats, date and time formats, and date-relatednames. Since the language information is already implied in the locale ID,it is not provided by CLocale. For the same reason, we ofteninterchangeably using the term locale and language.

Given a locale ID, one can get the corresponding CLocale instance byCLocale::getInstance($localeID) or CApplication::getLocale($localeID).

Info: Yii comes with locale data for nearly every language and region. The data is obtained from Common Locale Data Repository (CLDR). For each locale, only a subset of the CLDR data is provided as the original data contains much rarely used information.

For an Yii application, we differentiate its targetlanguage from sourcelanguage. The target language is the language(locale) of the users that the application is targeted at, while the sourcelanguage refers to the language (locale) that the application source filesare written in. Internationalization occurs only when the two languages aredifferent.

One can configure target language in theapplication configuration, orchange it dynamically before any internationalization occurs.

Tip: Sometimes, we may want to set the target language as the language preferred by a user (specified in user's browser preference). To do so, we can retrieve the user preferred language ID using CHttpRequest::preferredLanguage.

2. Translation

The most needed I18N feature is perhaps translation, including messagetranslation and view translation. The former translates a text message tothe desired language, while the latter translates a whole file to thedesired language.

A translation request consists of the object to be translated, the sourcelanguage that the object is in, and the target language that the objectneeds to be translated to. In Yii, the source language is default to theapplication source language while the targetlanguage is default to the application language.If the source and target languages are the same, translation will notoccur.

Message Translation

Message translation is done by calling Yii::t(). The methodtranslates the given message from sourcelanguage to targetlanguage.

When translating a message, its category has to be specified since amessage may be translated differently under different categories(contexts). The category yii is reserved for messages used by the Yiiframework core code.

Messages can contain parameter placeholders which will be replaced withthe actual parameter values when calling Yii::t(). Forexample, the following message translation request would replace the{alias} placeholder in the original message with the actual alias value.

  1. Yii::t('yii', 'Path alias "{alias}" is redefined.',
  2. array('{alias}'=>$alias))
Note: Messages to be translated must be constant strings. They should not contain variables that would change message content (e.g. "Invalid {$message} content."). Use parameter placeholders if a message needs to vary according to some parameters.

Translated messages are stored in a repository called messagesource. A message source is represented as an instance ofCMessageSource or its child class. When Yii::t() is invoked,it will look for the message in the message source and return itstranslated version if it is found.

Yii comes with the following types of message sources. You may also extendCMessageSource to create your own message source type.

  • CPhpMessageSource: the message translations are stored as key-valuepairs in a PHP array. The original message is the key and the translatedmessage is the value. Each array represents the translations for aparticular category of messages and is stored in a separate PHP script filewhose name is the category name. The PHP translation files for the samelanguage are stored under the same directory named as the locale ID. Andall these directories are located under the directory specified bybasePath.

  • CGettextMessageSource: the message translations are stored as GNUGettext files.

  • CDbMessageSource: the message translations are stored in databasetables. For more details, see the API documentation for CDbMessageSource.

A message source is loaded as an applicationcomponent. Yii pre-declares anapplication component named messages to storemessages that are used in user application. By default, the type of thismessage source is CPhpMessageSource and the base path for storing the PHPtranslation files is protected/messages.

In summary, in order to use message translation, the following steps areneeded:

Tip: The yiic tool in Yii can be used to manage message translations when CPhpMessageSource is used as the message source. Its message command can automatically extract messages to be translated from selected source files and merge them with existing translations if necessary.

Starting from version 1.0.10, when using CPhpMessageSource to manage message source,messages for an extension class (e.g. a widget, a module) can be specially managed and used. In particular, if a messagebelongs to an extension whose class name is Xyz, then the message category can be specifiedin the format of Xyz.categoryName. The corresponding message file will be assumed to beBasePath/messages/LanguageID/categoryName.php, where BasePath refers tothe directory that contains the extension class file. And when using Yii::t() totranslate an extension message, the following format should be used, instead:

  1. Yii::t('Xyz.categoryName', 'message to be translated')

Since version 1.0.2, Yii has added the support for choice format. Choice formatrefers to choosing a translated according to a given number value. For example,in English the word 'book' may either take a singular form or a plural formdepending on the number of books, while in other languages, the word may not havedifferent form (such as Chinese) or may have more complex plural form rules(such as Russian). Choice format solves this problem in a simple yet effective way.

To use choice format, a translated message must consist of a sequence ofexpression-message pairs separated by |, as shown below:

  1. 'expr1#message1|expr2#message2|expr3#message3'

where exprN refers to a valid PHP expression which evaluates to a boolean valueindicating whether the corresponding message should be returned. Only the messagecorresponding to the first expression that evaluates to true will be returned.An expression can contain a special variable named n (note, it is not $n)which will take the number value passed as the first message parameter. For example,assuming a translated message is:

  1. 'n==1#one book|n>1#many books'

and we are passing a number value 2 in the message parameter array whencalling Yii::t(), we would obtain many books as the finaltranslated message.

As a shortcut notation, if an expression is a number, it will be treated asn==Number. Therefore, the above translated message can be also be written as:

  1. '1#one book|n>1#many books'

File Translation

File translation is accomplished by callingCApplication::findLocalizedFile(). Given the path of a file to betranslated, the method will look for a file with the same name under theLocaleID subdirectory. If found, the file path will be returned;otherwise, the original file path will be returned.

File translation is mainly used when rendering a view. When calling one ofthe render methods in a controller or widget, the view files will betranslated automatically. For example, if the targetlanguage is zh_cn while the sourcelanguage is en_us, rendering a view namededit would resulting in searching for the view fileprotected/views/ControllerID/zh_cn/edit.php. If the file is found, thistranslated version will be used for rendering; otherwise, the fileprotected/views/ControllerID/edit.php will be rendered instead.

File translation may also be used for other purposes, for example,displaying a translated image or loading a locale-dependent data file.

3. Date and Time Formatting

Date and time are often in different formats in different countries orregions. The task of date and time formatting is thus to generate a date ortime string that fits for the specified locale. Yii providesCDateFormatter for this purpose.

Each CDateFormatter instance is associated with a target locale. To getthe formatter associated with the target locale of the whole application,we can simply access the dateFormatterproperty of the application.

The CDateFormatter class mainly provides two methods to format a UNIXtimestamp.

  • format: this method formats the given UNIXtimestamp into a string according to a customized pattern (e.g.$dateFormatter->format('yyyy-MM-dd',$timestamp)).

  • formatDateTime: this method formatsthe given UNIX timestamp into a string according to a pattern predefined inthe target locale data (e.g. short format of date, long format oftime).

4. Number Formatting

Like data and time, numbers may also be formatted differently in differentcountries or regions. Number formatting includes decimal formatting,currency formatting and percentage formatting. Yii providesCNumberFormatter for these tasks.

To get the number formatter associated with the target locale of the wholeapplication, we can access thenumberFormatter property of theapplication.

The following methods are provided by CNumberFormatter to format aninteger or double value.

  • format: this method formats the givennumber into a string according to a customized pattern (e.g.$numberFormatter->format('#,##0.00',$number)).

  • formatDecimal: this method formatsthe given number using the decimal pattern predefined in the target localedata.

  • formatCurrency: this methodformats the given number and currency code using the currency patternpredefined in the target locale data.

  • formatPercentage: this methodformats the given number using the percentage pattern predefined in thetarget locale data.

原文: https://www.yiichina.com/doc/guide/1.0/topics.i18n