`Connection`组件支持从服务器的负载均衡和故障转移,当第一次执行读查询时,会随即选择一个从服务器进行连接,如果连接失败则又选择另一个,如果所有从服务器都不可用,则会连接主服务器。你可以配置[[yii\db\Connection::serverStatusCache|server status cache]]来记住那些不能连接的从服务器,使Yii 在一段时间[[yii\db\Connection::serverRetryInterval]].内不会重复尝试连接那些根本不可用的从服务器.
> Info: Queries performed by calling [[yii\db\Command::execute()]] are considered as write queries, while
all other queries done through one of the "query" methods of [[yii\db\Command]] are read queries.
You can get the currently active slave connection via `Yii::$app->db->slave`.
The `Connection` component supports load balancing and failover between slaves.
When performing a read query for the first time, the `Connection` component will randomly pick a slave and
try connecting to it. If the slave is found "dead", it will try another one. If none of the slaves is available,
it will connect to the master. By configuring a [[yii\db\Connection::serverStatusCache|server status cache]],
a "dead" server can be remembered so that it will not be tried again during a
[[yii\db\Connection::serverRetryInterval|certain period of time]].
该参数如果没有明确配置会使用应用的 [[yii\base\Application::timeZone|from the application]] 参数。
日期格式根据不同区域输出不同的结果,如下例所示:
For example the date format call will output different results for different locales:
To display data in a more readable format for users, you may format them using the `formatter` [application component](structure-application-components.md).
By default the formatter is implemented by [[yii\i18n\Formatter]] which provides a set of methods to format data as
date/time, numbers, currencies, and other commonly used formats. You can use the formatter like the following,
```php
Yii::$app->formatter->locale = 'en-US';
echo Yii::$app->formatter->asDate('2014-01-01'); // 输出: January 1, 2014
Yii::$app->formatter->locale = 'de-DE';
echo Yii::$app->formatter->asDate('2014-01-01'); // 输出: 1. Januar 2014
Yii::$app->formatter->locale = 'ru-RU';
echo Yii::$app->formatter->asDate('2014-01-01'); // 输出: 1 января 2014 г.
You may customize the formatting rules by configuring the `formatter` component in the [application configuration](concept-configurations.md#application-configurations).
For example,
```php
'components' => [
'formatter' => [
'dateFormat' => 'dd.MM.yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => ' ',
'currencyCode' => 'EUR',
],
],
return [
'components' => [
'formatter' => [
'dateFormat' => 'dd.MM.yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => ' ',
'currencyCode' => 'EUR',
],
],
];
```
格式化日期和时间 <spanid="date-and-time"></span>
-------------------------------
Please refer to [[yii\i18n\Formatter]] for the properties that may be configured.
格式器类为格式化日期和时间提供了多个方法:
The formatter class provides different methods for formatting date and time values. These are:
The formatter supports the following output formats that are related with date and time:
格式器默认会使用一个快捷格式,它根据当前启用的区域来解析,
这样日期和时间会格式化成用户国家和语言通用的格式,
有四种不同的快捷格式:
- [[yii\i18n\Formatter::asDate()|date]]: the value is formatted as a date, e.g. `January 01, 2014`.
- [[yii\i18n\Formatter::asTime()|time]]: the value is formatted as a time, e.g. `14:23`.
- [[yii\i18n\Formatter::asDatetime()|datetime]]: the value is formatted as date and time, e.g. `January 01, 2014 14:23`.
- [[yii\i18n\Formatter::asTimestamp()|timestamp]]: the value is formatted as a [unix timestamp](http://en.wikipedia.org/wiki/Unix_time), e.g. `1412609982`.
- [[yii\i18n\Formatter::asRelativeTime()|relativeTime]]: the value is formatted as the time interval between a date
and now in human readable form e.g. `1 hour ago`.
- [[yii\i18n\Formatter::asDuration()|duration]]: the value is formatted as a duration in human readable format. e.g. `1 day, 2 minutes`.
A good API is *versioned*: changes and new features are implemented in new versions of the API instead of continually altering just one version. Unlike Web applications, with which you have full control of both the client-side and server-side
code, APIs are meant to be used by clients beyond your control. For this reason, backward
compatibility (BC) of the APIs should be maintained whenever possible. If a change that may break BC is necessary, you should introduce it in new version of the API, and bump up the version number. Existing clients can continue to use the old, working version of the API; and new or upgraded clients can get the new functionality in the new API version.
> Note: Rules with server names should NOT include the subfolder of the entry script in their patterns. For example, if the application is under `http://www.example.com/sandbox/blog`, then you should use the pattern
`http://www.example.com/posts` instead of `http://www.example.com/sandbox/blog/posts`. This will allow your application
to be deployed under any directory without the need to change your application code.
### URL Suffixes <spanid="url-suffixes"></span>
You may want to add suffixes to the URLs for various purposes. For example, you may add `.html` to the URLs so that they
look like URLs for static HTML pages; you may also add `.json` to the URLs to indicate the expected content type
of the response. You can achieve this goal by configuring the [[yii\web\UrlManager::suffix]] property like
the following in the application configuration:
```php
[
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'suffix' => '.html',
'rules' => [
// ...
],
],
],
]
```
The above configuration will allow the [[yii\web\UrlManager|URL manager]] to recognize requested URLs and also create
URLs with `.html` as their suffix.
> Tip: You may set `/` as the URL suffix so that the URLs all end with a slash.
> Note: When you configure a URL suffix, if a requested URL does not have the suffix, it will be considered as
an unrecognized URL. This is a recommended practice for SEO (search engine optimization).
Sometimes you may want to use different suffixes for different URLs. This can be achieved by configuring the
[[yii\web\UrlRule::suffix|suffix]] property of individual URL rules. When a URL rule has this property set, it will
override the suffix setting at the [[yii\web\UrlManager|URL manager]] level. For example, the following configuration
contains a customized URL rule which uses `.json` as its suffix instead of the global one `.html`.
```php
[
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'suffix' => '.html',
'rules' => [
// ...
[
'pattern' => 'posts',
'route' => 'post/index',
'suffix' => '.json',
],
],
],
],
]
```
### HTTP Methods <spanid="http-methods"></span>
When implementing RESTful APIs, it is commonly needed that the same URL be parsed into different routes according to
the HTTP methods being used. This can be easily achieved by prefixing the supported HTTP methods to the patterns of
the rules. If a rule supports multiple HTTP methods, separate the method names with commas. For example, the following
rules have the same pattern `post/<id:\d+>` with different HTTP method support. A request for `PUT post/100` will
be parsed into `post/create`, while a request for `GET post/100` will be parsed into `post/view`.
```php
[
'PUT,POST post/<id:\d+>' => 'post/create',
'DELETE post/<id:\d+>' => 'post/delete',
'post/<id:\d+>' => 'post/view',
]
```
> Note: If a URL rule contains HTTP method(s) in its pattern, the rule will only be used for parsing purpose.
It will be skipped when the [[yii\web\UrlManager|URL manager]] is called to create URLs.
> Tip: To simplify the routing of RESTful APIs, Yii provides a special URL rule class [[yii\rest\UrlRule]]
which is very efficient and supports some fancy features such as automatic pluralization of controller IDs.
For more details, please refer to the [Routing](rest-routing.md) section about developing RESTful APIs.
3. 检查该 ID 是否指向当前模块中 [[yii\base\Module::modules|modules]] 属性里的模块列表中的一个模块。如果是,会根据该模块表中的配置创建一个模块对象,然后会以新创建的模块为环境,跳回步骤二解析下一段路由。
4. 将该 ID 视为控制器 ID,并创建控制器对象。用下个步骤解析路由里剩下的片段。
5. 控制器会在他的 [[yii\base\Controller::actions()|action map(操作映射表)]]里搜索当前 ID。如果找得到,它会根据该映射表中的配置创建一个操作对象;反之,控制器则会尝试创建一个与该 ID
相对应,由某个 action 方法所定义的行内操作(inline action)。
When parsing or creating URLs, [[yii\web\UrlManager|URL manager]] examines URL rules in the order they are declared.
Therefore, you may consider adjusting the order of the URL rules so that more specific and/or more commonly used rules are placed before less used ones.
Yii provides convenient helper functions that allow you to encrypt/decrypt data using a secret key. The data is passed through the encryption function so that only the person which has the secret key will be able to decrypt it.
For example, we need to store some information in our database but we need to make sure only the user who has the secret key can view it (even if the application database is compromised):
```php
// $data and $secretKey are obtained from the form
It's also possible to use key instead of password via [[\yii\base\Security::encryptByKey()]] and
[[\yii\base\Security::decryptByKey()]].
Confirming Data Integrity
-------------------------
There are situations in which you need to verify that your data hasn't been tampered with by a third party or even corrupted in some way. Yii provides an easy way to confirm data integrity in the form of two helper functions.
Prefix the data with a hash generated from the secret key and data
```php
// $secretKey our application or user secret, $genuineData obtained from a reliable source
涉及到给操作命名时,你应该理解 Yii 如何处理操作 ID。操作 ID 总是被以小写处理,如果一个操作 ID 由多个单词组成,单词之间将由连字符连接(如 `create-comment`)。操作 ID 映射为方法名时移除了连字符,将每个单词首字母大写,并加上 `action` 前缀。 例子:操作 ID `create-comment` 相当于方法名 `actionCreateComment`。
涉及到给操作命名时,你应该理解 Yii 如何处理操作 ID。
操作 ID 总是被以小写处理,如果一个操作 ID 由多个单词组成,
单词之间将由连字符连接(如 `create-comment`)。操作 ID 映射为方法名时移除了连字符,
将每个单词首字母大写,并加上 `action` 前缀。
例子:操作 ID `create-comment` 相当于方法名 `actionCreateComment`。
> 补充:与操作一样,一个应用中控制器同样有唯一的 ID。控制器 ID 和操作 ID 使用同样的命名规则。控制器的类名源自于控制器 ID,移除了连字符,每个单词首字母大写,并加上 `Controller` 后缀。例子:控制器 ID `post-comment` 相当于控制器类名 `PostCommentController`。
> Info: 与操作一样,一个应用中控制器同样有唯一的 ID。控制器 ID 和操作 ID 使用同样的命名规则。控制器的类名源自于控制器 ID,移除了连字符,每个单词首字母大写,并加上 `Controller` 后缀。例子:控制器 ID `post-comment` 相当于控制器类名 `PostCommentController`。
>>>>>>> .merge_file_a02836
> 注意:与操作一样,一个应用中控制器同样有唯一的 ID。
控制器 ID 和操作 ID 使用同样的命名规则。
控制器的类名源自于控制器 ID,移除了连字符
,每个单词首字母大写,并加上 `Controller` 后缀。
例子:控制器 ID `post-comment` 相当于控制器类名 `PostCommentController`。
Standard installations of Yii result in both the framework and a project template being downloaded and installed.
A project template is a working Yii project implementing some basic features, such as login, contact form, etc.
Its code is organized in a recommended way. Therefore, it can serve as a good starting point for your projects.
In this and the next few sections, we will describe how to install Yii with the so-called *Basic Project Template* and
how to implement new features on top of this template. Yii also provides another template called
the [Advanced Project Template](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md) which is better used in a team development environment
to develop applications with multiple tiers.
> Info: The Basic Project Template is suitable for developing 90 percent of Web applications. It differs
from the Advanced Project Template mainly in how their code is organized. If you are new to Yii, we strongly
recommend you stick to the Basic Project Template for its simplicity yet sufficient functionalities.
Each Composer package must have a `composer.json` file in its root directory. The file contains the metadata about
the package. You may find complete specification about this file in the [Composer Manual](https://getcomposer.org/doc/01-basic-usage.md#composer-json-project-setup).
The following example shows the `composer.json` file for the `yiisoft/yii2-imagine` extension:
一些小部件可在[[yii\base\Widget::begin()]] 和 [[yii\base\Widget::end()]] 调用中使用数据内容。Some widgets can take a block of content which should be enclosed between the invocation of
> Note: If you need to use special characters such as `{`, `}`, `'`, `#`, wrap them in `'`:
>
```php
echo Yii::t('app', "Example of string with ''-escaped characters'': '{' '}' '{test}' {count,plural,other{''count'' value is # '#{}'}}", ['count' => 3]);
When nothing helps you may try making your application scalabe. A good introduction is provided in [Configuring a Yii2 Application for an Autoscaling Stack](https://github.com/samdark/yii2-cookbook/blob/master/book/scaling.md). For further reading you may refer to [Web apps performance and scaling](http://thehighload.com/).
Next, you'll want to modify the `composer.json` to reflect your template. Change the `name`, `description`, `keywords`, `homepage`, `license`, and `support` values
to describe your new template. Also adjust the `require`, `require-dev`, `suggest`, and other options to match your template's requirements.