Browse Source

Merge pull request #66 from yiichina/doc

Doc
tags/2.0.16
cuiliang 7 years ago committed by GitHub
parent
commit
9dbf5ed6a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 162
      docs/guide-zh-CN/caching-data.md
  2. 6
      docs/guide-zh-CN/caching-fragment.md
  3. 16
      docs/guide-zh-CN/concept-autoloading.md
  4. 60
      docs/guide-zh-CN/concept-behaviors.md
  5. 28
      docs/guide-zh-CN/concept-di-container.md
  6. 92
      docs/guide-zh-CN/start-installation.md
  7. 99
      docs/guide-zh-CN/tutorial-console.md

162
docs/guide-zh-CN/caching-data.md

@ -23,15 +23,21 @@ if ($data === false) {
// 这儿 $data 可以使用了。
```
从2.0.11版本开始, [缓存组件](#cache-components) 提供了[[yii\caching\Cache::getOrSet()|getOrSet()]] 方法来简化数据的取回、计算和存储。下面的代码逻辑和上一个例子是完全一样的:
从2.0.11版本开始, [缓存组件](#cache-components)
提供了[[yii\caching\Cache::getOrSet()|getOrSet()]] 方法来简化数据的取回、计算和存储。
下面的代码逻辑和上一个例子是完全一样的:
```php
$data = $cache->getOrSet($key, function () {
return $this->calculateSomething();
});
```
当缓存中有关联$key的数据时,将返回这个缓存的值。否则就执行匿名函数来计算出将要缓存的数据并返回它。
如果匿名函数需要作用域外的数据时,可以使用`use`语句把这些数据传递到匿名函数中。例如:
当缓存中有关联$key的数据时,将返回这个缓存的值。
否则就执行匿名函数来计算出将要缓存的数据并返回它。
如果匿名函数需要作用域外的数据时,可以使用`use`语句把这些数据传递到匿名函数中。
例如:
```php
$user_id = 42;
@ -40,7 +46,8 @@ $data = $cache->getOrSet($key, function () use ($user_id) {
});
```
> 注意:[[yii\caching\Cache::getOrSet()|getOrSet()]] 方法也支持缓存持续性和缓存依赖。请看[缓存过期](#cache-expiration) 和 [缓存依赖](#cache-dependencies) 来了解详细信息。
> 注意:[[yii\caching\Cache::getOrSet()|getOrSet()]] 方法也支持缓存持续性和缓存依赖。
请看[缓存过期](#cache-expiration) 和 [缓存依赖](#cache-dependencies) 来了解详细信息。
## 缓存组件 <span id="cache-components"></span>
@ -101,7 +108,10 @@ Yii 支持一系列缓存存储器,概况如下:
(例如:单一服务器,没有独立的负载均衡器等)最快的缓存方案。
* [[yii\caching\DbCache]]:使用一个数据库的表存储缓存数据。要使用这个缓存,
你必须创建一个与 [[yii\caching\DbCache::cacheTable]] 对应的表。
* [[yii\caching\DummyCache]]: 仅作为一个缓存占位符,不实现任何真正的缓存功能。
* [[yii\caching\ArrayCache]]: 仅通过将值存储在数组中来为当前请求提供缓存。
为了增强 ArrayCache 的性能,您可以通过将
[[yii\caching\ArrayCache::$serializer]] 设置为 `false` 来禁用已存储数据的序列化。
* [[yii\caching\DummyCache]]:仅作为一个缓存占位符,不实现任何真正的缓存功能。
这个组件的目的是为了简化那些需要查询缓存有效性的代码。例如,
在开发中如果服务器没有实际的缓存支持,用它配置一个缓存组件。
一个真正的缓存服务启用后,可以再切换为使用相应的缓存组件。
@ -137,16 +147,19 @@ Yii 支持一系列缓存存储器,概况如下:
如果该项数据不存在于缓存中或者已经过期/失效,则返回值 false。
* [[yii\caching\Cache::set()|set()]]:将一个由键指定的数据项存放到缓存中。
* [[yii\caching\Cache::add()|add()]]:如果缓存中未找到该键,则将指定数据存放到缓存中。
* [[yii\caching\Cache::getOrSet()|getOrSet()]]:返回由键指定的缓存项,或者执行回调函数,把函数的返回值用键来关联存储到缓存中,最后返回这个函数的返回值。
* [[yii\caching\Cache::getOrSet()|getOrSet()]]:返回由键指定的缓存项,或者执行回调函数,把函数的返回值用键来关联存储到缓存中,
最后返回这个函数的返回值。
* [[yii\caching\Cache::multiGet()|multiGet()]]:由指定的键获取多个缓存数据项。
* [[yii\caching\Cache::multiSet()|multiSet()]]:一次存储多个数据项到缓存中,每个数据都由一个键来指明。
* [[yii\caching\Cache::multiAdd()|multiAdd()]]:一次存储多个数据项到缓存中,每个数据都由一个键来指明。如果某个键已经存在,则略过该数据项不缓存。
* [[yii\caching\Cache::multiAdd()|multiAdd()]]:一次存储多个数据项到缓存中,每个数据都由一个键来指明。
如果某个键已经存在,则略过该数据项不缓存。
* [[yii\caching\Cache::exists()|exists()]]:返回一个值,指明某个键是否存在于缓存中。
* [[yii\caching\Cache::delete()|delete()]]:通过一个键,删除缓存中对应的值。
* [[yii\caching\Cache::flush()|flush()]]:删除缓存中的所有数据。
> 注意:千万别直接用`false`布尔值当做数据项缓存,因为[[yii\caching\Cache::get()|get()]]方法用
`false`作为返回值来表名对应的缓存项不存在。你可以把`false`放到一个数组里然后缓存这个数组来避免上述的混淆问题。
`false`作为返回值来表名对应的缓存项不存在。
你可以把`false`放到一个数组里然后缓存这个数组来避免上述的混淆问题。
有些缓存存储器如 MemCache,APC 支持以批量模式取回缓存值,这样可以节省取回缓存数据的开支。
[[yii\caching\Cache::multiGet()|multiGet()]]
@ -185,9 +198,9 @@ $value2 = $cache['var2']; // 等价于: $value2 = $cache->get('var2');
如你所见,该键包含了可唯一指定一个数据库表所需的所有必要信息。
> 注意:通过[[yii\caching\Cache::multiSet()|multiSet()]]或者[[yii\caching\Cache::multiAdd()|multiAdd()]]方法缓存的数据项的键,它的类型只能是字符串或整型,
> 注意:通过 [[yii\caching\Cache::multiSet()|multiSet()]] 或者 [[yii\caching\Cache::multiAdd()|multiAdd()]] 方法缓存的数据项的键,它的类型只能是字符串或整型,
如果你想使用较为复杂的键,可以通过
[[yii\caching\Cache::set()|set()]]或者[[yii\caching\Cache::add()|add()]]方法来存储。
[[yii\caching\Cache::set()|set()]] 或者 [[yii\caching\Cache::add()|add()]] 方法来存储。
当同一个缓存存储器被用于多个不同的应用时,应该为每个应用指定一个唯一的缓存键前缀以避免缓存键冲突。
可以通过配置 [[yii\caching\Cache::keyPrefix]] 属性实现。
@ -226,8 +239,9 @@ if ($data === false) {
}
```
从2.0.11开始,如果想自定义缓存的持续时间,你可以在缓存组件配置中设置[[yii\caching\Cache::$defaultDuration|defaultDuration]]成员属性的值。
这样设置会覆盖默认的缓存持续时间,且在使用[[yii\caching\Cache::set()|set()]]方法时不必每次都传递$duration参数。
从 2.0.11 开始,如果想自定义缓存的持续时间,你可以在缓存组件配置中设置 [[yii\caching\Cache::$defaultDuration|defaultDuration]] 成员属性的值。
这样设置会覆盖默认的缓存持续时间,且在使用 [[yii\caching\Cache::set()|set()]]
方法时不必每次都传递 `$duration` 参数。
### 缓存依赖 <span id="cache-dependencies"></span>
@ -262,10 +276,12 @@ $data = $cache->get($key);
- [[yii\caching\DbDependency]]:如果指定 SQL 语句的查询结果发生了变化,则依赖改变。
- [[yii\caching\ExpressionDependency]]:如果指定的 PHP 表达式执行结果发生变化,则依赖改变。
- [[yii\caching\FileDependency]]:如果文件的最后修改时间发生变化,则依赖改变。
- [[yii\caching\TagDependency]]: associates a cached data item with one or multiple tags. You may invalidate
the cached data items with the specified tag(s) by calling [[yii\caching\TagDependency::invalidate()]].
- [[yii\caching\TagDependency]]:将缓存的数据项与一个或多个标签相关联。 您可以通过调用
 [[yii\caching\TagDependency::invalidate()]] 来检查指定标签的缓存数据项是否有效。
> 注意:避免对带有缓存依赖的缓存项使用 [[yii\caching\Cache::exists()|exists()]] 方法,因为它不检测缓存依赖(如果有的话)是否有效,所以调用[[yii\caching\Cache::get()|get()]]可能返回`false`而调用[[yii\caching\Cache::exists()|exists()]]却返回`true`。
> 注意:避免对带有缓存依赖的缓存项使用 [[yii\caching\Cache::exists()|exists()]] 方法,
因为它不检测缓存依赖(如果有的话)是否有效,所以调用 [[yii\caching\Cache::get()|get()]]
可能返回 `false` 而调用 [[yii\caching\Cache::exists()|exists()]] 却返回 `true`
## 查询缓存 <span id="query-caching"></span>
@ -279,8 +295,8 @@ $data = $cache->get($key);
```php
$result = $db->cache(function ($db) {
// the result of the SQL query will be served from the cache
// if query caching is enabled and the query result is found in the cache
// SQL 查询的结果将从缓存中提供
// 如果启用查询缓存并且在缓存中找到查询结果
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
@ -299,93 +315,64 @@ $result = Customer::getDb()->cache(function ($db) {
你可以选择使用任一查询缓存机制。
上文所述的查询缓存的好处在于你可以指定更灵活的缓存依赖因此可能更加高效。
### 缓存冲刷 <span id="cache-flushing">
当你想让所有的缓存数据失效时,可以调用[[yii\caching\Cache::flush()]]。
冲刷缓存数据,你还可以从控制台调用`yii cache/flush`。
- `yii cache`: 列出应用中可用的缓存组件
- `yii cache/flush cache1 cache2`: 冲刷缓存组件`cache1`, `cache2` (可以传递多个用空格分开的缓存组件)
- `yii cache/flush-all`: 冲刷应用中所有的缓存组件
> 信息:默认情况下,控制台应用使用独立的配置文件。所以,为了上述命令发挥作用,请确保Web应用和控制台应用配置相同的缓存组件。
### 配置 <span id="query-caching-configs"></span>
Query caching has three global configurable options through [[yii\db\Connection]]:
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]: whether to turn on or off query caching.
It defaults to true. Note that to effectively turn on query caching, you also need to have a valid
cache, as specified by [[yii\db\Connection::queryCache|queryCache]].
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: this represents the number of seconds
that a query result can remain valid in the cache. You can use 0 to indicate a query result should
remain in the cache forever. This property is the default value used when [[yii\db\Connection::cache()]]
is called without specifying a duration.
* [[yii\db\Connection::queryCache|queryCache]]: 缓存应用组件的 ID。默认为 `'cache'`
只有在设置了一个有效的缓存应用组件时,查询缓存才会有效。
### Usages <span id="query-caching-usages"></span>
You can use [[yii\db\Connection::cache()]] if you have multiple SQL queries that need to take advantage of
query caching. The usage is as follows,
自 2.0.14 以后,您可以使用以下快捷方法:
```php
$duration = 60; // cache query results for 60 seconds.
$dependency = ...; // optional dependency
$result = $db->cache(function ($db) {
// ... perform SQL queries here ...
(new Query())->cache(7200)->all();
// and
User::find()->cache(7200)->all();
```
return $result;
}, $duration, $dependency);
```
### 配置 <span id="query-caching-configs"></span>
Any SQL queries in the anonymous function will be cached for the specified duration with the specified dependency.
If the result of a query is found valid in the cache, the query will be skipped and the result will be served
from the cache instead. If you do not specify the `$duration` parameter, the value of
[[yii\db\Connection::queryCacheDuration|queryCacheDuration]] will be used instead.
查询缓存通过 [[yii\db\Connection]] 有三个全局可配置选项:
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]:是否开启或关闭查询缓存,默认是`true`。注意,为了有效的开启查询缓存,你还需要配置一个由[[yii\db\Connection::queryCache|queryCache]]属性指定的缓存组件。
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: 这表示查询结果能够保持有效的秒数,设置为0的话,则会在缓存组件中永久缓存。这也是调用[[yii\db\Connection::cache()]]而没有指明缓存持续时间时的默认值。
* [[yii\db\Connection::queryCache|queryCache]]: 缓存应用组件的 ID。默认为 `'cache'`
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]:是否打开或关闭查询缓存。
它默认为 `true`。 请注意,要有效打开查询缓存,
 您还需要有一个由 [[yii\db\Connection::queryCache|queryCache]] 所指定的有效缓存。
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]:这表示查询结果在缓存中保持有效的秒数。
 您可以使用 0 来表示查询结果永久保留在缓存中。
该属性是在未指定持续时间的情况下调用 [[yii\db\Connection::cache()]]
使用的默认值。
* [[yii\db\Connection::queryCache|queryCache]]:缓存应用组件的 ID。默认为 `'cache'`
只有在设置了一个有效的缓存应用组件时,查询缓存才会有效。
### 用法 <span id="query-caching-usages"></span>
### 使用 <span id="query-caching-usages"></span>
如果一次有多个SQL查询想利用查询缓存,你可以用[[yii\db\Connection::cache()]] 。用法如下,
如果您有多个需要利用查询缓存的 SQL 查询,则可以使用 [[yii\db\Connection::cache()]]。
用法如下,
```php
$duration = 60; // cache query results for 60 seconds.
$dependency = ...; // optional dependency
$duration = 60; // 缓存查询结果 60 秒。
$dependency = ...; // 可选的依赖关系
$result = $db->cache(function ($db) {
// ... perform SQL queries here ...
// ... 在这里执行 SQL 查询 ...
return $result;
}, $duration, $dependency);
```
在匿名函数里的任何一个SQL查询都会伴随指定的duration和dependency来生成缓存。
如果一个SQL查询的结果在缓存中有效,那么这个SQl语句将会被跳过而它的查询结果会直接从缓存中读取。如果你没有指明`$duration`参数,那么使用[[yii\db\Connection::queryCacheDuration|queryCacheDuration]]属性。
在匿名函数里的任何一个 SQL 查询都将使用指定的依赖项缓存指定的持续时间
如果一个 SQL 查询的结果在缓存中有效,那么这个 SQl 语句将会被跳过而它的查询结果会直接从缓存中读取。
如果你没有指明 `$duration` 参数,
那么使用 [[yii\db\Connection::queryCacheDuration|queryCacheDuration]] 属性。
有时在`cache()`里,你可能不想缓存某些特殊的查询,这时你可以用[[yii\db\Connection::noCache()]]。
有时在`cache()`里,你可能不想缓存某些特殊的查询,
这时你可以用[[yii\db\Connection::noCache()]]。
```php
$result = $db->cache(function ($db) {
// SQL queries that use query caching
// 使用查询缓存的 SQL 查询
$db->noCache(function ($db) {
// SQL queries that do not use query caching
// 不使用查询缓存的 SQL 查询
});
@ -395,21 +382,22 @@ $result = $db->cache(function ($db) {
});
```
如果仅仅想缓存一个单独的查询,那么在建立查询命令时可以使用[[yii\db\Command::cache()]]。例如,
如果您只想为单个查询使用查询缓存,则可以在构建命令时调用 [[yii\db\Command::cache()]]。
例如,
```php
// use query caching and set query cache duration to be 60 seconds
// 使用查询缓存并将查询缓存持续时间设置为 60 秒
$customer = $db->createCommand('SELECT * FROM customer WHERE id=1')->cache(60)->queryOne();
```
也可以用[[yii\db\Command::noCache()]]来单独设置某些查询命令不缓存。例如,
您还可以使用 [[yii\db\Command::noCache()]] 禁用单个命令的查询缓存。例如,
```php
$result = $db->cache(function ($db) {
// SQL queries that use query caching
// 使用查询缓存的 SQL 查询
// do not use query caching for this command
   // 对此命令不使用查询缓存
$customer = $db->createCommand('SELECT * FROM customer WHERE id=1')->noCache()->queryOne();
// ...
@ -429,3 +417,17 @@ $result = $db->cache(function ($db) {
因此,如果查询结果的大小超出了该限制,
则会导致缓存失败。
### 缓存冲刷 <span id="cache-flushing">
当你想让所有的缓存数据失效时,可以调用[[yii\caching\Cache::flush()]]。
冲刷缓存数据,你还可以从控制台调用`yii cache/flush`。
- `yii cache`: 列出应用中可用的缓存组件
- `yii cache/flush cache1 cache2`: 冲刷缓存组件`cache1`, `cache2`
(可以传递多个用空格分开的缓存组件)
- `yii cache/flush-all`: 冲刷应用中所有的缓存组件
> 信息:默认情况下,控制台应用使用独立的配置文件。
所以,为了上述命令发挥作用,请确保Web应用和控制台应用配置相同的缓存组件。

6
docs/guide-zh-CN/caching-fragment.md

@ -1,5 +1,5 @@
片段缓存
================
=======
片段缓存指的是缓存页面内容中的某个片段。例如,一个页面显示了逐年销售额的摘要表格,
可以把表格缓存下来,以消除每次请求都要重新生成表格的耗时。
@ -47,7 +47,7 @@ if ($this->beginCache($id, ['duration' => 3600])) {
}
```
If the option is not set, it will take the default value 60, which means the cached content will expire in 60 seconds.
如果该选项未设置,则它将采用默认值 60,这意味着缓存的内容将在 60 秒后过期。
### 依赖 <span id="dependencies"></span>
@ -175,3 +175,5 @@ if ($this->beginCache($id1)) {
代码的返回值被看作是动态内容。这段代码将在每次请求时都执行,
无论其外层的片段缓存是否被存储。
> 注意:从版本 2.0.14 开始,动态内容 API 通过 [[yii\base\DynamicContentAwareInterface]] 接口及其 [[yii\base\DynamicContentAwareTrait]] 特质开放。
 举个例子,你可以参考 [[yii\widgets\FragmentCache]] 类。

16
docs/guide-zh-CN/concept-autoloading.md

@ -1,9 +1,9 @@
类自动加载(Autoloading)
=================
======================
Yii 依靠[类自动加载机制](http://www.php.net/manual/en/language.oop5.autoload.php)来定位和包含所需的类文件。
它提供一个高性能且完美支持[PSR-4 标准](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md)
([中文汉化](https://github.com/hfcorriez/fig-standards/blob/zh_CN/%E6%8E%A5%E5%8F%97/PSR-4-autoloader.md))的自动加载器。
的自动加载器。
该自动加载器会在引入框架文件 `Yii.php` 时安装好。
> 注意:为了简化叙述,本篇文档中我们只会提及类的自动加载。
@ -11,7 +11,7 @@ Yii 依靠[类自动加载机制](http://www.php.net/manual/en/language.oop5.aut
使用 Yii 自动加载器 <span id="using-yii-autoloader"></span>
------------------------
-----------------
要使用 Yii 的类自动加载器,你需要在创建和命名类的时候遵循两个简单的规则:
@ -37,11 +37,11 @@ $classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php');
因此,你可以把前端的类放在 `frontend` 命名空间,而后端的类放在 `backend`
这样这些类就可以被 Yii 自动加载了。
To add a custom namespace to the autoloader you need to define an alias for the base directory of the namespace using [[Yii::setAlias()]].
For example to load classes in the `foo` namespace that are located in the `path/to/foo` directory you will call `Yii::setAlias('@foo', 'path/to/foo')`.
要将自定义命名空间添加到自动加载器,您需要使用 [[Yii::setAlias()]] 为命名空间的根目录定义别名。
例如,要加载位于 `path/to/foo` 目录中 `foo` 命名空间中的类,您将调用 `Yii::setAlias('@foo', 'path/to/foo')`
类映射表(Class Map) <span id="class-map"></span>
---------
------------------
Yii 类自动加载器支持**类映射表**功能,该功能会建立一个从类的名字到类文件路径的映射。
当自动加载器加载一个文件时,他首先检查映射表里有没有该类。
@ -88,7 +88,7 @@ require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
-----------------------------
Yii 自动加载器支持自动加载[扩展](structure-extensions.md)的类。唯一的要求是它需要在 `composer.json` 文件里正确地定义 `autoload` 部分。
请参考 [Composer 文档(英文)](https://getcomposer.org/doc/04-schema.md#autoload)
([中文汉化](https://github.com/5-say/composer-doc-cn/blob/master/cn-introduction/04-schema.md#autoload)),来了解如何正确描述 `autoload` 的更多细节。
请参考 [Composer 文档](https://getcomposer.org/doc/04-schema.md#autoload)
来了解如何正确描述 `autoload` 的更多细节。
在你不使用 Yii 的自动加载器时,Composer 的自动加载器仍然可以帮你自动加载扩展内的类。

60
docs/guide-zh-CN/concept-behaviors.md

@ -1,5 +1,5 @@
行为
=========
===
行为是 [[yii\base\Behavior]] 或其子类的实例。
行为,也称为 [mixins](http://en.wikipedia.org/wiki/Mixin),
@ -9,8 +9,8 @@
此外,行为通过组件能响应被触发的[事件](basic-events.md),从而自定义或调整组件正常执行的代码。
定义行为
-----------
定义行为 <span id="defining-behaviors"></span>
------
要定义行为,通过继承 [[yii\base\Behavior]] 或其子类来建立一个类。如:
@ -54,7 +54,7 @@ class MyBehavior extends Behavior
need to override [[yii\base\Behavior::canGetProperty()]] and/or [[yii\base\Behavior::canSetProperty()]] as well.
处理事件
-------------
-------
如果要让行为响应对应组件的事件触发,
就应覆写 [[yii\base\Behavior::events()]] 方法,如:
@ -192,8 +192,8 @@ $component->attachBehaviors([
详情请参考
[配置](concept-configurations.md#configuration-format)章节。
使用行为
---------------
使用行为 <span id="using-behaviors"></span>
-------
使用行为,必须像前文描述的一样先把它附加到 [[yii\base\Component|component]] 类或其子类。一旦行为附加到组件,就可以直接使用它。
@ -233,8 +233,8 @@ $behaviors = $component->getBehaviors();
```
移除行为
------------
移除行为 <span id="detaching-behaviors"></span>
-------
要移除行为,可以调用 [[yii\base\Component::detachBehavior()]] 方法用行为相关联的名字实现:
@ -249,8 +249,8 @@ $component->detachBehaviors();
```
使用 `TimestampBehavior`
----------------------------
使用 `TimestampBehavior` <span id="using-timestamp-behavior"></span>
-----------------------
最后以 [[yii\behaviors\TimestampBehavior]] 的讲解来结尾,
这个行为支持在 [[yii\db\ActiveRecord|Active Record]]
@ -291,10 +291,10 @@ class User extends ActiveRecord
`created_at``updated_at` 属性;
* 当记录更新时,行为将当前时间戳赋值给 `updated_at` 属性。
> 注意:For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp.
> 注意:对于上述实现使用MySQL数据库,请将列 (`created_at`, `updated_at`) 定义为 int(11) 作为 UNIX 时间戳。
With that code in place, if you have a `User` object and try to save it, you will find its `created_at` and `updated_at` are automatically
filled with the current UNIX timestamp:
有了以上这段代码,如果你有一个 `User` 对象并且试图保存它,你会发现它的 `created_at``updated_at`
被当前的UNIX时间戳自动填充:
```php
$user = new User;
@ -312,26 +312,26 @@ $user->touch('login_time');
```
其它行为
---------------
-------
There are several built-in and external behaviors available:
有几种内置和外部行为可用:
- [[yii\behaviors\BlameableBehavior]] - automatically fills the specified attributes with the current user ID.
- [[yii\behaviors\SluggableBehavior]] - automatically fills the specified attribute with a value that can be used
as a slug in a URL.
- [[yii\behaviors\AttributeBehavior]] - automatically assigns a specified value to one or multiple attributes of
an ActiveRecord object when certain events happen.
- [yii2tech\ar\softdelete\SoftDeleteBehavior](https://github.com/yii2tech/ar-softdelete) - provides methods to soft-delete
and soft-restore ActiveRecord i.e. set flag or status which marks record as deleted.
- [yii2tech\ar\position\PositionBehavior](https://github.com/yii2tech/ar-position) - allows managing records order in an
integer field by providing reordering methods.
- [[yii\behaviors\BlameableBehavior]] - 使用当前用户 ID 自动填充指定的属性。
- [[yii\behaviors\SluggableBehavior]] - 自动填充指定的属性,其值可以在 URL
中用作 slug。
- [[yii\behaviors\AttributeBehavior]] - 在发生特定事件时自动为 ActiveRecord 对象的一个或多个属性
指定一个指定的值。
- [yii2tech\ar\softdelete\SoftDeleteBehavior](https://github.com/yii2tech/ar-softdelete) - 提供软删除和软恢复 ActiveRecord 的
方法。即将记录标记为已删除的设置标记或状态。
- [yii2tech\ar\position\PositionBehavior](https://github.com/yii2tech/ar-position) - 允许通过提供重新排序方法来
管理整数字段中的记录顺序。
比较行为与 Traits <span id="comparison-with-traits"></span>
----------------------
While behaviors are similar to [traits](http://www.php.net/traits) in that they both "inject" their
properties and methods to the primary class, they differ in many aspects. As explained below, they
both have pros and cons. They are more like complements to each other rather than alternatives.
虽然行为类似于 [traits](http://www.php.net/traits),它们都将自己的属性和方法“注入”到主类中,
但它们在许多方面有所不同。如下所述,他们都有优点和缺点。
它们更像互补类而非替代类。
### 使用行为的原因 <span id="pros-for-behaviors"></span>
@ -342,7 +342,7 @@ both have pros and cons. They are more like complements to each other rather tha
行为无须修改组件类就可动态附加到组件或移除。
要使用 traits,必须修改使用它的类。
Behaviors are configurable while traits are not.
行为是可配置的,而 traits 则不可行。
Behaviors can customize the code execution of a component by responding to its events.
@ -354,7 +354,7 @@ properties or methods.
### 使用 Traits 的原因 <span id="pros-for-traits"></span>
Traits are much more efficient than behaviors as behaviors are objects that take both time and memory.
Traits 比行为更有效,因为行为是既需要时间又需要内存的对象。
IDEs are more friendly to traits as they are a native language construct.
因为 IDE 是一种本地语言结构,所以它们对 Traits 更友好。

28
docs/guide-zh-CN/concept-di-container.md

@ -1,5 +1,5 @@
依赖注入容器
==============================
==========
依赖注入(Dependency Injection,DI)容器就是一个对象,它知道怎样初始化并配置对象及其依赖的所有对象。
[Martin 的文章](http://martinfowler.com/articles/injection.html) 已经解释了 DI 容器为什么很有用。
@ -7,7 +7,7 @@
依赖注入 <span id="dependency-injection"></span>
--------------------
-------
Yii 通过 [[yii\di\Container]] 类提供 DI 容器特性。
它支持如下几种类型的依赖注入:
@ -40,7 +40,7 @@ $foo = new Foo($bar);
```
### Method Injection <span id="method-injection"></span>
### 方法注入 <span id="method-injection"></span>
Usually the dependencies of a class are passed to the constructor and are available inside of the class during the whole lifecycle.
With Method Injection it is possible to provide a dependency that is only needed by a single method of the class
@ -126,7 +126,7 @@ $container->set('Foo', function () {
$foo = $container->get('Foo');
```
To hide the complex logic for building a new object, you may use a static class method as callable. For example,
要省略构建新对象的复杂逻辑,可以使用静态类方法作为可调用的方法。例如,
```php
class FooBuilder
@ -144,7 +144,7 @@ $container->set('Foo', ['app\helper\FooBuilder', 'build']);
$foo = $container->get('Foo');
```
By doing so, the person who wants to configure the `Foo` class no longer needs to be aware of how it is built.
这样做的话,想要配置 `Foo` 类的人不再需要知道它是如何构建的。
注册依赖关系 <span id="registering-dependencies"></span>
@ -372,10 +372,10 @@ class HotelController extends Controller
现在如果你再次访问这个控制器,一个 `app\components\BookingService`
的实例就会被创建并被作为第三个参数注入到控制器的构造器中。
Advanced Practical Usage <span id="advanced-practical-usage"></span>
---------------
高级实用性 <span id="advanced-practical-usage"></span>
---------
Say we work on API application and have:
比如说我们在 API 应用方面工作:
- `app\components\Request` class that extends `yii\web\Request` and provides additional functionality
- `app\components\Response` class that extends `yii\web\Response` and should have `format` property
@ -404,7 +404,7 @@ It is possible to configure multiple definitions at once, passing configuration
Iterating over the configuration array, the methods will call [[yii\di\Container::set()|set()]]
or [[yii\di\Container::setSingleton()|setSingleton()]] respectively for each item.
The configuration array format is:
配置数组格式为:
- `key`: class name, interface name or alias name. The key will be passed to the
[[yii\di\Container::set()|set()]] method as a first argument `$class`.
@ -412,7 +412,7 @@ The configuration array format is:
documentation for the `$definition` parameter. Will be passed to the [[set()]] method as
the second argument `$definition`.
For example, let's configure our container to follow the aforementioned requirements:
例如,让我们配置我们的容器以遵循上述要求:
```php
$container->setDefinitions([
@ -447,7 +447,7 @@ a third argument. To set the constructor parameters, you may use the following c
- `value`: array of two elements. The first element will be passed to the [[yii\di\Container::set()|set()]] method as the
second argument `$definition`, the second one — as `$params`.
Let's modify our example:
让我们来修改我们的例子:
```php
$container->setDefinitions([
@ -473,8 +473,8 @@ You might notice `Instance::of('tempFileStorage')` notation. It means, that the
will implicitly provide a dependency registered with the name of `tempFileStorage` and pass it as the first argument
of `app\storage\DocumentsWriter` constructor.
> 注意:[[yii\di\Container::setDefinitions()|setDefinitions()]] and [[yii\di\Container::setSingletons()|setSingletons()]]
methods are available since version 2.0.11.
> 注意:[[yii\di\Container::setDefinitions()|setDefinitions()]]  [[yii\di\Container::setSingletons()|setSingletons()]]
方法从版本 2.0.11 开始可用。
Another step on configuration optimization is to register some dependencies as singletons.
A dependency registered via [[yii\di\Container::set()|set()]] will be instantiated each time it is needed.
@ -532,5 +532,3 @@ Yii 在依赖住入(DI)容器之上实现了它的[服务定位器](concept-
当一个服务定位器尝试创建一个新的对象实例时,它会把调用转发到 DI 容器。
后者将会像前文所述那样自动解决依赖关系。

92
docs/guide-zh-CN/start-installation.md

@ -10,7 +10,7 @@
在本章节和以后的章节,我们将会介绍如何去安装Yii和所谓的*基本的应用程序模板*和如何去实现这个模板上的新特性。
Yii当然也提供了其它模板叫
[高级的应用程序模板](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md),
[高级的应用程序模板](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide-zh-CN/README.md),
它是更好应用于在一个团队开发环境中去开发多层级的应用程序。
> 信息:这个基本的应用程序模板是适合于开发90%的Web应用程序。
@ -21,7 +21,7 @@ Yii当然也提供了其它模板叫
通过 Composer 安装 <span id="installing-via-composer"></span>
-----------------------
### Installing Composer
### 安装 Composer
如果还没有安装 Composer,你可以按 [getcomposer.org](https://getcomposer.org/download/) 中的方法安装。
在 Linux 和 Mac OS X 中可以运行如下命令:
@ -33,33 +33,51 @@ mv composer.phar /usr/local/bin/composer
在 Windows 中,你需要下载并运行 [Composer-Setup.exe](https://getcomposer.org/Composer-Setup.exe)。
如果遇到任何问题或者想更深入地学习 Composer,请参考 [Composer 文档(英文)](https://getcomposer.org/doc/),
[Composer 中文](https://github.com/5-say/composer-doc-cn)。
如果遇到任何问题或者想更深入地学习 Composer,
请参考 [Composer 文档(英文)](https://getcomposer.org/doc/)。
如果你已经安装有 Composer 请确保使用的是最新版本,
你可以用 `composer self-update` 命令更新 Composer 为最新版本。
Composer 安装后,切换到一个可通过 Web 访问的目录,执行如下命令即可安装 Yii :
In this guide all composer commands assume you have installed composer [globally](https://getcomposer.org/doc/00-intro.md#globally)
so that it is available as the `composer` command. If you are using the `composer.phar` in the local directory instead,
you have to adjust the example commands accordingly.
If you had Composer already installed before, make sure you use an up to date version. You can update Composer
by running `composer self-update`.
> Note: During the installation of Yii, Composer will need to request a lot of information from the Github API.
> The number of requests depends on the number of dependencies your application has and may be bigger than the
> **Github API rate limit**. If you hit this limit, Composer may ask for your Github login credentials to obtain
> a Github API access token. On fast connections you may hit this limit earlier than Composer can handle so we
> recommend to configure the access token before installing Yii.
> Please refer to the [Composer documentation about Github API tokens](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)
> for instructions on how to do this.
### Installing Yii <span id="installing-from-composer"></span>
composer global require "fxp/composer-asset-plugin:^1.4.1"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
With Composer installed, you can install Yii application template by running the following command
under a Web-accessible folder:
第一条命令安装 [Composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/),
它是通过 Composer 管理 bower 和 npm 包所必须的,此命令全局生效,一劳永逸。
第二条命令会将 Yii 安装在名为 `basic` 的目录中。如果你想使用其它目录名称,你可以选择其他目录名称。
```bash
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
```
> 注意:在安装过程中 Composer 可能会询问你 GitHub 账户的认证信息,因为可能在使用中超过了 GitHub API (对匿名用户的)使用限制。因为 Composer 需要为所有扩展包从 GitHub
> 中获取大量信息,所以超限非常正常。(译注:也意味着作为程序猿没有 GitHub 账号,就真不能愉快地玩耍了)登陆 GitHub 之后可以得到更高的 API 限额,这样 Composer 才能正常运行。更多细节请参考 [Composer
> 文档](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)(该段 Composer中文文档[期待您的参与](https://github.com/5-say/composer-doc-cn/blob/master/cn-introduction/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens))。
This will install the latest stable version of Yii application template in a directory named `basic`.
You can choose a different directory name if you want.
> 提示:如果你想安装 Yii 的最新开发版本,可以使用以下命令代替,
> 它添加了一个 [stability 选项](https://getcomposer.org/doc/04-schema.md#minimum-stability)([中文版](https://github.com/5-say/composer-doc-cn/blob/master/cn-introduction/04-schema.md#minimum-stability)):
> Info: If the `composer create-project` command fails you may also refer to the
> [Troubleshooting section of the Composer Documentation](https://getcomposer.org/doc/articles/troubleshooting.md)
> for common errors. When you have fixed the error, you can resume the aborted installation
> by running `composer update` inside of the `basic` directory.
> Tip: If you want to install the latest development version of Yii, you may use the following command instead,
> which adds a [stability option](https://getcomposer.org/doc/04-schema.md#minimum-stability):
>
> ```bash
> composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
> ```
>
> 注意,Yii 的开发版(dev 版)不应该用于生产环境中,它可能会破坏运行中的代码。
> Note that the development version of Yii should not be used for production as it may break your running code.
通过归档文件安装 <span id="installing-from-archive-file"></span>
@ -79,7 +97,7 @@ Composer 安装后,切换到一个可通过 Web 访问的目录,执行如下
其他安装方式 <span id="other-installation-options"></span>
--------------------------
----------
上文介绍了两种安装 Yii 的方法,
安装的同时也会创建一个立即可用的 Web 应用程序。
@ -90,11 +108,35 @@ Composer 安装后,切换到一个可通过 Web 访问的目录,执行如下
* 如果你只想安装核心框架,然后从零开始构建整个属于你自己的应用程序模版,
可以参考[从头构建自定义模版](tutorial-start-from-scratch.md)一节的介绍。
* 如果你要开发一个更复杂的应用,可以更好地适用于团队开发环境的,
你可以考虑安装[高级应用模版](tutorial-advanced-app.md)。
你可以考虑安装[高级应用模版](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide-zh-CN/README.md)。
Installing Assets <span id="installing-assets"></span>
-----------------
Yii relies on [Bower](http://bower.io/) and/or [NPM](https://www.npmjs.org/) packages for the asset (CSS and JavaScript) libraries installation.
It uses Composer to obtain these libraries, allowing PHP and CSS/JavaScript package versions to resolve at the same time.
This can be achieved either by usage of [asset-packagist.org](https://asset-packagist.org) or [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/).
Please refer to [Assets documentation](structure-assets.md) for more details.
You may want to either manage your assets via native Bower/NPM client, use CDN or avoid assets installation entirely.
In order to prevent assets installation via Composer, add the following lines to your 'composer.json':
```json
"replace": {
"bower-asset/jquery": ">=1.11.0",
"bower-asset/inputmask": ">=3.2.0",
"bower-asset/punycode": ">=1.3.0",
"bower-asset/yii2-pjax": ">=2.0.0"
},
```
> Note: in case of bypassing asset installation via Composer, you are responsible for the assets installation and resolving
> version collisions. Be prepared for possible inconsistencies among asset files from different extensions.
验证安装的结果 <span id="verifying-installation"></span>
--------------------------
------------
当安装完成之后,
或配置你的Web服务器(看下面的文章)或使用[内置Web Server](https://secure.php.net/manual/en/features.commandline.webserver.php),
@ -161,6 +203,8 @@ URL `http://www.example.com/index.php` 访问而不是 `http://www.example.com/b
没有修改其 Web 服务器配置的权限,你依然可以通过调整应用的结构来提升安全性。
详情请参考[共享主机环境](tutorial-shared-hosting.md) 一章。
> Info: If you are running your Yii application behind a reverse proxy, you might need to configure
> [Trusted proxies and headers](runtime-requests.md#trusted-proxies) in the request component.
### 推荐使用的 Apache 配置 <span id="recommended-apache-configuration"></span>
@ -180,6 +224,9 @@ DocumentRoot "path/to/basic/web"
# 如果请求的不是真实文件或目录,分发请求至 index.php
RewriteRule . index.php
# if $showScriptName is false in UrlManager, do not allow accessing URLs with script name
RewriteRule ^index.php/ - [L,R=404]
# ...其它设置...
</Directory>
```
@ -217,6 +264,11 @@ server {
#}
#error_page 404 /404.html;
# deny accessing php files for the /assets directory
location ~ ^/assets/.*\.php$ {
deny all;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

99
docs/guide-zh-CN/tutorial-console.md

@ -50,12 +50,12 @@ yii <route> [--option1=value1 --option2=value2 ... argument1 argument2 ...]
yii migrate/up 5 --migrationTable=migrations
```
> **注意**: 当在控制台使用 `*` 时, 不要忘记像 `"*"` 一样用引号来引起来,
> 注意:当在控制台使用 `*` 时, 不要忘记像 `"*"` 一样用引号来引起来,
> 为了防止在 shell 中执行命令时被当成当前目录下的所有文件名。
入口脚本 <span id="entry-script"></span>
----------------
-------
控制台应用程序的入口脚本相当于用于 Web 应用程序的 `index.php` 入口文件。
控制台入口脚本通常被称为 `yii`,位于应用程序的根目录。
@ -69,6 +69,7 @@ yii migrate/up 5 --migrationTable=migrations
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
@ -106,8 +107,55 @@ exit($exitCode);
> ```
控制台命令完成 <span id="console-command-completion"></span>
------------
自动完成命令参数在使用 shell 时非常有用。
从版本 2.0.11 开始,`./yii` 命令为 Bash 和 ZSH 提供了自动完成功能。
### Bash 完成
确保安装完毕。对于大多数安装,它默认是可用的。
放置完成脚本在 `/etc/bash_completion.d/`
curl -L https://raw.githubusercontent.com/yiisoft/yii2/master/contrib/completion/bash/yii -o /etc/bash_completion.d/yii
对于临时使用,您可以将文件放入当前目录,并通过 `source yii` 将其包含在当前会话中。
如果全局安装,您可能需要重新启动终端或`source ~/.bashrc` 来激活它。
查看 [Bash 手册](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html)
了解将完成脚本添加到您的环境的其他方法。
### ZSH 完成
将完成脚本放入完成目录中,例如使用 `~/.zsh/completion/`
```
mkdir -p ~/.zsh/completion
curl -L https://raw.githubusercontent.com/yiisoft/yii2/master/contrib/completion/zsh/_yii -o ~/.zsh/completion/_yii
```
将目录包含在 `$fpath` 中,例如,通过将其添加到 `~/.zshrc`
```
fpath=(~/.zsh/completion $fpath)
```
确保 `compinit` 被加载或通过在 `~/.zshrc` 中加入完成
```
autoload -Uz compinit && compinit -i
```
然后重新加载您的 shell
```
exec $SHELL -l
```
创建你自己的控制台命令 <span id="create-command"></span>
----------------------
------------------
### 控制台的控制器和行为
@ -126,15 +174,15 @@ exit($exitCode);
当运行一个命令,你可以指定使用语法 `--OptionName=OptionValue` 选项的值。
这将分配 `OptionValue` 到控制器类的 `OptionName` 属性。
If the default value of an option is of an array type and you set this option while running the command,
the option value will be converted into an array by splitting the input string on any commas.
如果选项的默认值是数组类型,并且在运行该命令时设置了该选项,
通过在任何逗号分割输入字符串将选项值转换为数组。
### Options Aliases
### 选项别名
Since version 2.0.8 console command provides [[yii\console\Controller::optionAliases()]] method to add
aliases for options.
从版本 2.0.8 起控制台命令提供 [[yii\console\Controller::optionAliases()]]
方法来为选项添加别名。
To define an alias, override [[yii\console\Controller::optionAliases()]] in your controller, for example:
要定义别名,请在控制器中覆盖 [[yii\console\Controller::optionAliases()]],例如:
```php
namespace app\commands;
@ -162,7 +210,7 @@ class HelloController extends Controller
}
```
Now, you can use the following syntax to run the command:
现在,您可以使用以下语法来运行该命令:
```
./yii hello -m=hello
@ -219,10 +267,19 @@ public function actionIndex()
}
```
你可以使用一些预定义的常数
有一些预定义的常量可以使用。在类 [[yii\console\ExitCode]] 中被定义
- `Controller::EXIT_CODE_NORMAL` 值为 `0`;
- `Controller::EXIT_CODE_ERROR` 值为 `1`.
```php
public function actionIndex()
{
if (/* some problem */) {
echo "A problem occurred!\n";
return ExitCode::UNSPECIFIED_ERROR;
}
// do something
return ExitCode::OK;
}
```
为控制器定义有意义的常量,以防有更多的错误代码类型,这会是一个很好的实践。
@ -243,3 +300,19 @@ $this->stdout("Hello?\n", Console::BOLD);
$name = $this->ansiFormat('Alex', Console::FG_YELLOW);
echo "Hello, my name is $name.";
```
### 表格
从版本 2.0.13 开始,有一个小部件允许您在控制台中格式化表数据。使用方法如下:
```php
echo Table::widget([
'headers' => ['Project', 'Status', 'Participant'],
'rows' => [
['Yii', 'OK', '@samdark'],
['Yii', 'OK', '@cebe'],
],
]);
```
有关详细信息,请参阅 [[yii\console\widgets\Table|API documentation]].

Loading…
Cancel
Save