Yii Framework Official Guide Series Supplement 48 - Special Topic: Internationalization (I18N)

黄舟
Release: 2023-03-05 19:06:02
Original
1122 people have browsed it



Internationalization (Translator’s Note: Internationalization, because there are 18 letters between I and n, so it is often abbreviated as I18N) It refers to the process of designing an application software that can adapt to the needs of different languages ​​and regions without making major engineering changes. Internationalization is particularly important for web applications because potential users may come from all corners of the world.

Yii provides support for I18N in several aspects

  • It provides localized data for every possible language and variant.

  • It provides translation services for information and documents.

  • It provides localization-based date and time formats.

  • It provides local dialect-based number format.

In the following sections, we will explain the above aspects in detail.

1. Region and Language

The region is a series of parameters that defines the user's language, the user's country, and any special parameters the user wants to see in their interface. It is usually identified by an ID that contains a language ID and a locale ID. For example, the ID en_US represents the English region and the United States. To maintain consistency, all region IDs in Yii are normalized to lowercase languageID or languageID_regionID (for example, en, en_us ).

Region data is represented by a CLocale instance. It provides locale-based information including currency symbols, numeric symbols, date and time formats, and date-related names. Since language information is already implemented by locale IDs, CLocale is no longer provided. For the same reason, we often use the words "region" and "language" interchangeably.

With a region ID, you can obtain the corresponding CLocale instance through CLocale::getInstance($localeID) or CApplication::getLocale($localeID).

Information: Yii contains regionalized data for almost all languages ​​and regions. This data comes from Common Locale Data Repository (CLDR). Within each region, only partial data from the CLDR is provided because the original CLDR data contains a large amount of less commonly used information. Starting with version 1.1.0, users can also use their own custom zone data. You only need to configure the CApplication::localeDataPath attribute to the directory containing custom locale data. Please refer to the files located in the framework/i18n/data directory to create a custom zone data file.

In a Yii application, we distinguish between its target language and source language. The target language is the language (region) of the application's intended users, while the source language refers to the language (region) written in the application's source code. Internationalization only occurs if the two languages ​​are different.

You can set the target language in the application configuration, or dynamically set this parameter before internationalization occurs.

Tip: Sometimes, we want to set the target language to the language used by the user (the one specified in the user's browser options). Just use CHttpRequest::preferredLanguage to get the language set by the user.

2. Translation

Probably the most used one in I18N is translation, including information translation and view translation. The former translates a text message into the desired language, and the latter translates an integrated document into the desired language.

A translation request contains the object to be translated, the source language of the object, and the target language to which the object needs to be translated. In Yii, the source language defaults to Application Source Language and the target language defaults to Application Language. If both are in the same language, translation will not happen.

Information translation

Information translation is achieved by calling Yii::t(). This method translates information from the source language to the target language.

When translating a message, its category must be specified, because a message may have different translations in different categories or contexts. Classification yii is reserved for use by the Yii framework core only.

The information can contain parameter placeholders, which will be replaced by the actual parameter values ​​when calling Yii::t(). For example, the following message translation request will replace the {alias} placeholder in the original message with the actual alias value.


Yii::t('app', 'Path alias "{alias}" is redefined.',
    array('{alias}'=>$alias))
Copy after login

Note: The information to be translated must be a constant string. They cannot contain variables that might change the content of the message (e.g. "Invalid {$message} content."). If a message needs to be changed through some parameters, please use parameter placeholders.

翻译过的信息会存储在一个叫做 信息源(message source) 的库中。 信息源是一个 CMessageSource 或其子类的实例。当 Yii::t() 被调用时, 它将从信息源中查找相应的信息,如果找到了,就会返回翻译后的版本。

Yii 含有如下几种信息源。你也可以扩展 CMessageSource 创建自己的信息源类型。

  • CPhpMessageSource: 信息的翻译存储在一个 PHP 的 键值对 数组中。 原始信息为键,翻译后的信息为值。每个数组表示一个特定信息分类的翻译,分别存储在不同的 PHP 脚本文件中,文件名即分类名。 针对同一种语言的 PHP 翻译文件存储在同一个以区域 ID 命名的目录中。而所有的这些目录位于 basePath 指定的目录中。

  • CGettextMessageSource: 信息的翻译存储在 GNU Gettext 文件中。

  • CDbMessageSource: 信息的翻译存储在数据库的表中。

信息源是作为一个 应用程序组件 载入的。 Yii 预定义了一个名为 messages 的应用程序组件以存储用户程序中用到的信息。 默认情况下,此信息源的类型是 CPhpMessageSource ,而存储这些 PHP 翻译文件的目录是protected/messages

总体来说,要实现信息翻译,需要执行如下几步:

  1. 在合适的位置调用 Yii::t() ;

  2. 以 protected/messages/LocaleID/CategoryName.php 的格式创建 PHP 翻译文件。 每个文件简单的返回一个信息翻译数组。 注意,这是假设你使用默认的 CPhpMessageSource 存储翻译信息。

  3. 配置 CApplication::sourceLanguage 和 CApplication::language。

提示: 使用 CPhpMessageSource 作为信息源时,Yii 中的 yiic 工具可用于管理信息翻译。 它的message 命令可以自动从所选的源文件中提取要翻译的信息,并在需要时将其合并为现存的翻译。 关于使用 message 命令的更多信息,请执行 yiic help message

从版本 1.0.10 起,当使用 CPhpMessageSource 管理信息源时, 扩展类(例如一个 widget 小物件,一个模块)中的信息可以以一种特殊的方式管理并使用。 具体来说,如果一条信息属于一个类名为 Xyz 的扩展,那么分类的名字可以以 Xyz.categoryName 的格式指定。 相应的信息文件就是BasePath/messages/LanguageID/categoryName.php ,其中 BasePath 是指包含此扩展类文件的那个目录。 当使用 Yii::t() 翻译一条扩展信息时,需要使用如下格式:


Yii::t('Xyz.categoryName', '要翻译的信息');
Copy after login

从 1.0.2 起,Yi 添加了对 choice format 的支持。Choice format 是指选择按照一个给定数字的值选择一条翻译。例如,在英语中,视不同的数量,单词 'book' 可以有一个单数形式或者一个复数形式。而在其他语言中, 这个词可能就没有不同的形式(例如汉语)或者有更复杂的复数规则(例如俄语)。 Choice format 以一种简单而又高效的方式解决了这个问题。

要使用 choice format,翻译的信息必须包含一个由 | 分割的 “表达式-信息” 对序列。如下所示:


'expr1#message1|expr2#message2|expr3#message3'
Copy after login

其中 exprN 表示一个有效的 PHP 表达式,它会计算出一个布尔型的值,以确定相应的信息是否应该被返回。 只有第一个返回值为 true 的表达式对应的信息会被返回。 一个表达式可以包含一个特殊的变量 n (注意,它不是$n),它带有通过第一个信息参数传递的数字的值。 例如,假设有如下一条翻译信息:


'n==1#one book|n>1#many books'
Copy after login

而我们在调用 Yii::t() 时在参数数组中传递了数字值 2 , 我们就会得到 many books 作为最终的翻译信息。

作为一种简便写法,如果一个表达式是一个数字,它将被视为等同于 n==Number。因此,上面的翻译信息也可以写为如下格式:


'1#one book|n>1#many books'
Copy after login

File Translation

File translation is completed by calling CApplication::findLocalizedFile(). Given a path to a file to be translated, this method will look for a file with the same file name in the region ID subdirectory. If found, the path to this file is returned; otherwise, the path to the original file is returned.

File translation is mainly used to render a view. When any rendering method is called in a controller or widget, the view file will be automatically translated. For example, if the target language is zh_cn and the source language is en_us, when rendering a view named edit, the program will look for protected/views /ControllerID/zh_cn/edit.php View file. If this file is found, it will be rendered via this translated version. Otherwise, the file protected/views/ControllerID/edit.php will be used for rendering.

File translation can also be used for other purposes, for example, displaying a translated image, or loading a region-based data file.

For practical examples of information translation and file translation, please refer to this article: How to use Yii::t() in the Yii framework to implement text information translation and file translation

3. Date and time Format

Date and time usually have different formats in different countries and regions. The task of date and time format sum is to generate a date or time string that conforms to the specified locale format. To achieve this purpose, Yii provides CDateFormatter.

Each CDateFormatter instance is associated with a target area. To obtain the formatter associated with the target region of the entire application, simply access the application's dateFormatter property.

The CDateFormatter class mainly provides two methods to format UNIX timestamps.

  • format: This method formats the given UNIX timestamp into a string using a custom pattern (e.g. $dateFormatter->format('yyyy- MM-dd',$timestamp)).

  • formatDateTime: This method formats the given UNIX timestamp into a string (e.g. short of date) using a pattern predefined in the target zone data Format, time’s long format).

4. Number formatting

Similar to dates and times, numbers may also have different formats between different countries or regions. Number formatting includes decimal formatting, currency formatting and percentage formatting. Yii provides CNumberFormatter to accomplish these tasks.

To obtain the formatter associated with the target range of the entire application, simply access the application's numberFormatter property.

CNumberFormatter provides the following methods that can be used to format integer or double values

  • format: This method formats the given number into a through a custom pattern String (e.g. $numberFormatter->format('#,##0.00',$number)).

  • formatDecimal: This method formats the given number using the predefined decimal pattern in the target zone data.

  • formatCurrency: This method formats the given number using the predefined currency pattern in the target region's data.

  • formatPercentage: This method formats the given number using the predefined percentage pattern in the target range data.

The above is the content of Yii Framework Official Guide Series Supplement 48 - Special Topic: Internationalization (I18N). For more related content, please pay attention to the PHP Chinese website (www.php.cn) !


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!