


Yii Framework Official Guide Series Supplement 48 - Special Topic: Internationalization (I18N)
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))
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
。
总体来说,要实现信息翻译,需要执行如下几步:
在合适的位置调用 Yii::t() ;
以
protected/messages/LocaleID/CategoryName.php
的格式创建 PHP 翻译文件。 每个文件简单的返回一个信息翻译数组。 注意,这是假设你使用默认的 CPhpMessageSource 存储翻译信息。配置 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', '要翻译的信息');
从 1.0.2 起,Yi 添加了对 choice format 的支持。Choice format 是指选择按照一个给定数字的值选择一条翻译。例如,在英语中,视不同的数量,单词 'book' 可以有一个单数形式或者一个复数形式。而在其他语言中, 这个词可能就没有不同的形式(例如汉语)或者有更复杂的复数规则(例如俄语)。 Choice format 以一种简单而又高效的方式解决了这个问题。
要使用 choice format,翻译的信息必须包含一个由 |
分割的 “表达式-信息” 对序列。如下所示:
'expr1#message1|expr2#message2|expr3#message3'
其中 exprN
表示一个有效的 PHP 表达式,它会计算出一个布尔型的值,以确定相应的信息是否应该被返回。 只有第一个返回值为 true 的表达式对应的信息会被返回。 一个表达式可以包含一个特殊的变量 n
(注意,它不是$n
),它带有通过第一个信息参数传递的数字的值。 例如,假设有如下一条翻译信息:
'n==1#one book|n>1#many books'
而我们在调用 Yii::t() 时在参数数组中传递了数字值 2 , 我们就会得到 many books
作为最终的翻译信息。
作为一种简便写法,如果一个表达式是一个数字,它将被视为等同于 n==Number
。因此,上面的翻译信息也可以写为如下格式:
'1#one book|n>1#many books'
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’slong
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) !

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the development of globalization and the popularity of the Internet, more and more websites and applications have begun to strive to achieve internationalization and multi-language support functions to meet the needs of different groups of people. In order to realize these functions, developers need to use some advanced technologies and frameworks. In this article, we will introduce how to use the Gin framework to implement internationalization and multi-language support capabilities. The Gin framework is a lightweight web framework written in Go language. It is efficient, easy to use and flexible, and has become the preferred framework for many developers. besides,

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

Use the FastAPI framework to build international Web applications. FastAPI is a high-performance Python Web framework that combines Python type annotations and high-performance asynchronous support to make developing Web applications simpler, faster, and more reliable. When building an international Web application, FastAPI provides convenient tools and concepts that can make the application easily support multiple languages. Below I will give a specific code example to introduce how to use the FastAPI framework to build

Nowadays, with the continuous development of Internet technology, more and more websites and applications need to support multi-language and internationalization. In web development, using frameworks can greatly simplify the development process. This article will introduce how to use the Webman framework to achieve internationalization and multi-language support, and provide some code examples. 1. What is the Webman framework? Webman is a lightweight PHP-based framework that provides rich functionality and easy-to-use tools for developing web applications. One of them is internationalization and multi-

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

How to use the Hyperf framework for international support With the rapid development of globalization, many applications need to have multi-language support functions to meet the needs of users in different countries and regions. As a lightweight, high-performance framework, the Hyperf framework provides international support functions and can help developers quickly develop multi-language applications. This article will introduce how to use internationalization functions in the Hyperf framework and provide corresponding code examples. 1. Configure multi-language support. First, you need to configure the Hyperf configuration file.

1. Prepare the database to create a new table for multilingual data, including the following fields: CREATETABLEtranslations(idINTNOTNULLAUTO_INCREMENT,localeVARCHAR(255)NOTNULL,keyVARCHAR(255)NOTNULL,valueTEXTNOTNULL,PRIMARYKEY(id)); 2. Set the language switching mechanism on the website Add a language switcher to the top or sidebar to allow users to select their preferred language. //Get the current language $current_locale=isset($_GET["locale"])?$_

How to deal with multi-language and internationalization issues in PHP development requires specific code examples. With the development of the Internet, people's demand for multi-language and internationalization is getting higher and higher. In PHP development, how to effectively handle multi-language and internationalization issues has become an important task that developers need to solve. Handling of character encoding In PHP development, we must first ensure that character encoding is handled correctly. In multi-language environments, using UTF-8 encoding is the most common choice. You can add the following code to the head of the PHP file: header('C
