From 6862e0648a440763949d2cc50ad946ad81dbce9a Mon Sep 17 00:00:00 2001 From: Mef45 Date: Mon, 9 Apr 2018 13:20:29 +0500 Subject: [PATCH 01/12] Fix typo in input-forms.md (#16062) [skip ci] --- docs/guide-ru/input-forms.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide-ru/input-forms.md b/docs/guide-ru/input-forms.md index 417b4d1..2475a1a 100644 --- a/docs/guide-ru/input-forms.md +++ b/docs/guide-ru/input-forms.md @@ -161,7 +161,7 @@ Pjax::end(); В `jQuery.serializeArray()` имеются определённые проблемы [при работе с файлами](https://github.com/jquery/jquery/issues/2321) и -[значениями кнопом типа submit](https://github.com/jquery/jquery/issues/2321). +[значениями кнопок типа submit](https://github.com/jquery/jquery/issues/2321). Они не будут исправлены и признаны устаревшими в пользу класса`FormData` из HTML5. Это означет, что поддержка файлов и значений submit-кнопок через AJAX или виджет From 9ba943c4ad40436e79e3c955e5bc19a5ff919f34 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 9 Apr 2018 10:27:03 +0200 Subject: [PATCH 02/12] Update start-prerequisites.md (#16060) [skip ci] --- docs/guide/start-prerequisites.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/guide/start-prerequisites.md b/docs/guide/start-prerequisites.md index 63f1936..484a097 100644 --- a/docs/guide/start-prerequisites.md +++ b/docs/guide/start-prerequisites.md @@ -1,10 +1,11 @@ # What do you need to know -Yii learning curve is not as steep as other PHP frameworks but still it requires some beforehand knowledge. +The Yii learning curve is not as steep as other PHP frameworks but still there are some things you should learn before starting with Yii. ## PHP Yii is a PHP framework so make sure you [read and understand language reference](http://php.net/manual/en/langref.php). +When developing with Yii you will be writing code in an object oriented fashion, so make sure you are familiar with [Classes and Objects](https://secure.php.net/manual/en/language.oop5.basic.php) as well as [namespaces](https://secure.php.net/manual/en/language.namespaces.php). ## Object oriented programming @@ -17,6 +18,6 @@ manage that complexity. ## Command line and composer Yii extensively uses de-facto standard PHP package manager, [Composer](https://getcomposer.org/) so make sure you read -and understand its guide. If you are not familiar with using command line it is time to start trying. Once you +and understand its [guide](https://getcomposer.org/doc/01-basic-usage.md). If you are not familiar with using command line it is time to start trying. Once you learn the basics you'll never want to work without it. From 8f277c1b3078dcd75748255e30d4c2a7de90bcc2 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 9 Apr 2018 23:21:16 +0200 Subject: [PATCH 03/12] fix typo thanks @maxim-niko --- docs/guide-ru/db-query-builder.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide-ru/db-query-builder.md b/docs/guide-ru/db-query-builder.md index e2de4c1..21335f4 100644 --- a/docs/guide-ru/db-query-builder.md +++ b/docs/guide-ru/db-query-builder.md @@ -215,7 +215,7 @@ $userQuery = (new Query())->select('id')->from('user'); $query->where(['id' => $userQuery]); ``` -Используя формат массива, Yii автоматически призяывает значения массива как параметры, потому в отличие от [строкового формата](#string-format), +Используя формат массива, Yii автоматически привязывает значения массива как параметры, потому в отличие от [строкового формата](#string-format), привязывать параметры вручную не требуется. Обратите внимание, что Yii никогда НЕ экранирует имена столбцов (ключи массива), потому если вы используете как ключ массива переменню, полученную от пользователя без дополнительной проверки, ваше приложение становится подверженным атаке через SQL инъекцию. Чтобы избежать этого, используйте для имён столбцов только проверененные данные, From 91c369d8df33aa200cf949528b7809e71f422ea6 Mon Sep 17 00:00:00 2001 From: cuiliang Date: Tue, 10 Apr 2018 15:22:29 +0800 Subject: [PATCH 04/12] zh-CN translation (#16069) * Update caching-fragment.md * Update caching-data.md * Update concept-autoloading.md * Update concept-behaviors.md * Update concept-di-container.md * Update tutorial-console.md * Update start-installation.md * Update structure-controllers.md * Update structure-controllers.md * add blocktypes.json and fix blocks name * update concept-behaviors.md * translation * Update intro-upgrade-from-v1.md * documentation_style_guide.md * Update concept-configurations.md --- docs/guide-zh-CN/blocktypes.json | 4 +- docs/guide-zh-CN/caching-data.md | 166 +++++++++--------- docs/guide-zh-CN/caching-fragment.md | 6 +- docs/guide-zh-CN/concept-autoloading.md | 18 +- docs/guide-zh-CN/concept-behaviors.md | 76 ++++----- docs/guide-zh-CN/concept-configurations.md | 8 - docs/guide-zh-CN/concept-di-container.md | 84 +++++---- docs/guide-zh-CN/concept-properties.md | 2 +- docs/guide-zh-CN/db-active-record.md | 2 +- docs/guide-zh-CN/db-dao.md | 8 +- docs/guide-zh-CN/db-migrations.md | 5 +- docs/guide-zh-CN/documentation_style_guide.md | 87 ++++++++++ docs/guide-zh-CN/helper-html.md | 2 +- docs/guide-zh-CN/input-forms.md | 2 +- docs/guide-zh-CN/input-validation.md | 4 +- docs/guide-zh-CN/intro-upgrade-from-v1.md | 45 ++--- docs/guide-zh-CN/output-data-widgets.md | 4 +- docs/guide-zh-CN/output-formatting.md | 2 +- docs/guide-zh-CN/output-theming.md | 2 +- docs/guide-zh-CN/rest-quick-start.md | 4 +- docs/guide-zh-CN/rest-routing.md | 2 +- docs/guide-zh-CN/rest-versioning.md | 2 +- docs/guide-zh-CN/runtime-handling-errors.md | 2 +- docs/guide-zh-CN/runtime-requests.md | 6 +- docs/guide-zh-CN/runtime-responses.md | 6 +- docs/guide-zh-CN/runtime-routing.md | 188 +++++++++++++-------- docs/guide-zh-CN/runtime-sessions-cookies.md | 2 +- docs/guide-zh-CN/start-databases.md | 6 +- docs/guide-zh-CN/start-forms.md | 6 +- docs/guide-zh-CN/start-gii.md | 4 +- docs/guide-zh-CN/start-hello.md | 4 +- docs/guide-zh-CN/start-installation.md | 98 ++++++++--- docs/guide-zh-CN/start-workflow.md | 2 +- .../structure-application-components.md | 2 +- docs/guide-zh-CN/structure-applications.md | 6 +- docs/guide-zh-CN/structure-assets.md | 14 +- docs/guide-zh-CN/structure-controllers.md | 10 +- docs/guide-zh-CN/structure-extensions.md | 10 +- docs/guide-zh-CN/structure-filters.md | 2 +- docs/guide-zh-CN/structure-models.md | 8 +- docs/guide-zh-CN/structure-modules.md | 4 +- docs/guide-zh-CN/structure-widgets.md | 2 +- docs/guide-zh-CN/test-overview.md | 20 +-- docs/guide-zh-CN/tutorial-console.md | 99 +++++++++-- docs/guide-zh-CN/tutorial-mailing.md | 2 +- .../guide-zh-CN/tutorial-yii-as-micro-framework.md | 8 +- 46 files changed, 648 insertions(+), 398 deletions(-) create mode 100644 docs/guide-zh-CN/documentation_style_guide.md diff --git a/docs/guide-zh-CN/blocktypes.json b/docs/guide-zh-CN/blocktypes.json index 67d0c6e..b049d3a 100644 --- a/docs/guide-zh-CN/blocktypes.json +++ b/docs/guide-zh-CN/blocktypes.json @@ -1,6 +1,6 @@ { "Warning:": "警告:", "Note:": "注意:", - "Info:": "补充:", + "Info:": "信息:", "Tip:": "提示:" -} \ No newline at end of file +} diff --git a/docs/guide-zh-CN/caching-data.md b/docs/guide-zh-CN/caching-data.md index c4384f3..ad05a7e 100644 --- a/docs/guide-zh-CN/caching-data.md +++ b/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) { }); ``` -> Note: [[yii\caching\Cache::getOrSet()|getOrSet()]] 方法也支持缓存持续性和缓存依赖。请看[缓存过期](#cache-expiration) 和 [缓存依赖](#cache-dependencies) 来了解详细信息。 +> Note: [[yii\caching\Cache::getOrSet()|getOrSet()]] 方法也支持缓存持续性和缓存依赖。 + 请看[缓存过期](#cache-expiration) 和 [缓存依赖](#cache-dependencies) 来了解详细信息。 ## 缓存组件 @@ -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()]]:删除缓存中的所有数据。 -> Note: 千万别直接用`false`布尔值当做数据项缓存,因为[[yii\caching\Cache::get()|get()]]方法用 -`false`作为返回值来表名对应的缓存项不存在。你可以把`false`放到一个数组里然后缓存这个数组来避免上述的混淆问题。 +> Note: 千万别直接用 `false` 布尔值当做数据项缓存,因为 [[yii\caching\Cache::get()|get()]] 方法用 +`false` 作为返回值来表名对应的缓存项不存在。 +你可以把 `false` 放到一个数组里然后缓存这个数组来避免上述的混淆问题。 有些缓存存储器如 MemCache,APC 支持以批量模式取回缓存值,这样可以节省取回缓存数据的开支。 [[yii\caching\Cache::multiGet()|multiGet()]] @@ -185,9 +198,9 @@ $value2 = $cache['var2']; // 等价于: $value2 = $cache->get('var2'); 如你所见,该键包含了可唯一指定一个数据库表所需的所有必要信息。 -> Note: 通过[[yii\caching\Cache::multiSet()|multiSet()]]或者[[yii\caching\Cache::multiAdd()|multiAdd()]]方法缓存的数据项的键,它的类型只能是字符串或整型, +> Note: 通过 [[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` 参数。 ### 缓存依赖 @@ -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()]] 来检查指定标签的缓存数据项是否有效。 -> Note: 避免对带有缓存依赖的缓存项使用 [[yii\caching\Cache::exists()|exists()]] 方法,因为它不检测缓存依赖(如果有的话)是否有效,所以调用[[yii\caching\Cache::get()|get()]]可能返回`false`而调用[[yii\caching\Cache::exists()|exists()]]却返回`true`。 +> Note: 避免对带有缓存依赖的缓存项使用 [[yii\caching\Cache::exists()|exists()]] 方法, +因为它不检测缓存依赖(如果有的话)是否有效,所以调用 [[yii\caching\Cache::get()|get()]] +可能返回 `false` 而调用 [[yii\caching\Cache::exists()|exists()]] 却返回 `true`。 ## 查询缓存 @@ -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(); }); @@ -294,98 +310,69 @@ $result = Customer::getDb()->cache(function ($db) { }); ``` -> 信息:有些 DBMS (例如:[MySQL](http://dev.mysql.com/doc/refman/5.1/en/query-cache.html)) +> Info: 有些 DBMS (例如:[MySQL](http://dev.mysql.com/doc/refman/5.1/en/query-cache.html)) 也支持数据库服务器端的查询缓存。 你可以选择使用任一查询缓存机制。 上文所述的查询缓存的好处在于你可以指定更灵活的缓存依赖因此可能更加高效。 - -### 缓存冲刷 - -当你想让所有的缓存数据失效时,可以调用[[yii\caching\Cache::flush()]]。 - -冲刷缓存数据,你还可以从控制台调用`yii cache/flush`。 - - `yii cache`: 列出应用中可用的缓存组件 - - `yii cache/flush cache1 cache2`: 冲刷缓存组件`cache1`, `cache2` (可以传递多个用空格分开的缓存组件) - - `yii cache/flush-all`: 冲刷应用中所有的缓存组件 - -> 信息:默认情况下,控制台应用使用独立的配置文件。所以,为了上述命令发挥作用,请确保Web应用和控制台应用配置相同的缓存组件。 - - -### 配置 - -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 - -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); -``` +### 配置 -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'`。 只有在设置了一个有效的缓存应用组件时,查询缓存才会有效。 -### 用法 +### 使用 -如果一次有多个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) { 因此,如果查询结果的大小超出了该限制, 则会导致缓存失败。 + +### 缓存冲刷 + +当你想让所有的缓存数据失效时,可以调用[[yii\caching\Cache::flush()]]。 + +冲刷缓存数据,你还可以从控制台调用`yii cache/flush`。 + - `yii cache`: 列出应用中可用的缓存组件 + - `yii cache/flush cache1 cache2`: 冲刷缓存组件`cache1`, `cache2` + (可以传递多个用空格分开的缓存组件) + - `yii cache/flush-all`: 冲刷应用中所有的缓存组件 + +> Info: 默认情况下,控制台应用使用独立的配置文件。 +所以,为了上述命令发挥作用,请确保Web应用和控制台应用配置相同的缓存组件。 + diff --git a/docs/guide-zh-CN/caching-fragment.md b/docs/guide-zh-CN/caching-fragment.md index 8287e6c..d74a936 100644 --- a/docs/guide-zh-CN/caching-fragment.md +++ b/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 秒后过期。 ### 依赖 @@ -175,3 +175,5 @@ if ($this->beginCache($id1)) { 代码的返回值被看作是动态内容。这段代码将在每次请求时都执行, 无论其外层的片段缓存是否被存储。 +> Note: 从版本 2.0.14 开始,动态内容 API 通过 [[yii\base\DynamicContentAwareInterface]] 接口及其 [[yii\base\DynamicContentAwareTrait]] 特质开放。 +  举个例子,你可以参考 [[yii\widgets\FragmentCache]] 类。 diff --git a/docs/guide-zh-CN/concept-autoloading.md b/docs/guide-zh-CN/concept-autoloading.md index 840a6c7..d473612 100644 --- a/docs/guide-zh-CN/concept-autoloading.md +++ b/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` 时安装好。 > Note: 为了简化叙述,本篇文档中我们只会提及类的自动加载。 @@ -11,7 +11,7 @@ Yii 依靠[类自动加载机制](http://www.php.net/manual/en/language.oop5.aut 使用 Yii 自动加载器 ------------------------- +----------------- 要使用 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) ---------- +------------------ Yii 类自动加载器支持**类映射表**功能,该功能会建立一个从类的名字到类文件路径的映射。 当自动加载器加载一个文件时,他首先检查映射表里有没有该类。 @@ -80,7 +80,7 @@ require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'; 不过这样做的话,类的加载效率会下降, 且你必须遵循 Composer 所设定的规则,从而让你的类满足可以被自动加载的要求。 -> 信息:若你不想要使用 Yii 的自动加载器,你必须创建一个你自己版本的 `Yii.php` 文件, +> Info: 若你不想要使用 Yii 的自动加载器,你必须创建一个你自己版本的 `Yii.php` 文件, 并把它包含进你的[入口脚本](structure-entry-scripts.md)里。 @@ -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 的自动加载器仍然可以帮你自动加载扩展内的类。 diff --git a/docs/guide-zh-CN/concept-behaviors.md b/docs/guide-zh-CN/concept-behaviors.md index 8c71a96..7cece5e 100644 --- a/docs/guide-zh-CN/concept-behaviors.md +++ b/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),从而自定义或调整组件正常执行的代码。 -定义行为 ------------ +定义行为 +------ 要定义行为,通过继承 [[yii\base\Behavior]] 或其子类来建立一个类。如: @@ -50,11 +50,11 @@ class MyBehavior extends Behavior > Tip: 在行为内部可以通过 [[yii\base\Behavior::owner]] 属性访问行为已附加的组件。 -> Note: In case [[yii\base\Behavior::__get()]] and/or [[yii\base\Behavior::__set()]] method of behavior is overridden you -need to override [[yii\base\Behavior::canGetProperty()]] and/or [[yii\base\Behavior::canSetProperty()]] as well. +> Note: 如果 [[yii\base\Behavior::__get()]] 和/或 [[yii\base\Behavior::__set()]] 行为方法被覆盖, +> 则需要覆盖 [[yii\base\Behavior::canGetProperty()]] 和/或 [[yii\base\Behavior::canSetProperty()]]。 处理事件 -------------- +------- 如果要让行为响应对应组件的事件触发, 就应覆写 [[yii\base\Behavior::events()]] 方法,如: @@ -192,8 +192,8 @@ $component->attachBehaviors([ 详情请参考 [配置](concept-configurations.md#configuration-format)章节。 -使用行为 ---------------- +使用行为 +------- 使用行为,必须像前文描述的一样先把它附加到 [[yii\base\Component|component]] 类或其子类。一旦行为附加到组件,就可以直接使用它。 @@ -233,8 +233,8 @@ $behaviors = $component->getBehaviors(); ``` -移除行为 ------------- +移除行为 +------- 要移除行为,可以调用 [[yii\base\Component::detachBehavior()]] 方法用行为相关联的名字实现: @@ -242,15 +242,15 @@ $behaviors = $component->getBehaviors(); $component->detachBehavior('myBehavior1'); ``` -也可以移除**全部**行为: +也可以移除*全部*行为: ```php $component->detachBehaviors(); ``` -使用 `TimestampBehavior` ----------------------------- +使用 `TimestampBehavior` +----------------------- 最后以 [[yii\behaviors\TimestampBehavior]] 的讲解来结尾, 这个行为支持在 [[yii\db\ActiveRecord|Active Record]] @@ -291,10 +291,10 @@ class User extends ActiveRecord `created_at` 和 `updated_at` 属性; * 当记录更新时,行为将当前时间戳赋值给 `updated_at` 属性。 -> Note: For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp. +> Note: 对于上述实现使用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 ---------------------- -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),它们都将自己的属性和方法“注入”到主类中, +但它们在许多方面有所不同。如下所述,他们都有优点和缺点。 +它们更像互补类而非替代类。 ### 使用行为的原因 @@ -342,19 +342,19 @@ 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. +行为可以通过响应事件来定制组件的代码执行。 -When there can be name conflicts among different behaviors attached to the same component, the conflicts are -automatically resolved by prioritizing the behavior attached to the component first. -Name conflicts caused by different traits requires manual resolution by renaming the affected -properties or methods. +当附属于同一组件的不同行为之间可能存在名称冲突时, +通过优先考虑附加到该组件的行为, +自动解决冲突。由不同 traits 引起的名称冲突需要通过 +重命名受影响的属性或方法进行手动解决。 ### 使用 Traits 的原因 -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 更友好。 diff --git a/docs/guide-zh-CN/concept-configurations.md b/docs/guide-zh-CN/concept-configurations.md index 3d8b3b1..4512cff 100644 --- a/docs/guide-zh-CN/concept-configurations.md +++ b/docs/guide-zh-CN/concept-configurations.md @@ -80,13 +80,9 @@ Yii::configure($object, $config); ## 使用配置 -<<<<<<< HEAD Yii 中的配置可以用在很多场景。本章开头我们展示了如何使用 [[Yii::creatObject()]] 根据配置信息创建对象。本小节将介绍配置的两种 主要用法 —— 配置应用与配置小部件。 -======= -Yii 中的配置可以用在很多场景。本章开头我们展示了如何使用 [[Yii::createObject()]] 根据配置信息创建对象。本小节将介绍配置的两种主要用法 —— 配置应用与配置小部件。 ->>>>>>> upstream/master ### 应用的配置 @@ -242,14 +238,10 @@ $config = require 'path/to/web.php'; ## 默认配置 -<<<<<<< HEAD [[Yii::createObject()]] 方法基于[依赖注入容器](concept-di-container.md)实现。 使用 [[Yii::creatObject()]] 创建对象时,可以附加一系列**默认配置**到指定类的任何实例。 默认配置还可以在[入口脚本](runtime-bootstrapping.md) 中调用 `Yii::$container->set()` 来定义。 -======= -[[Yii::createObject()]] 方法基于[依赖注入容器](concept-di-container.md)实现。使用 [[Yii::createObject()]] 创建对象时,可以附加一系列**默认配置**到指定类的任何实例。默认配置还可以在[入口脚本](runtime-bootstrapping.md)中调用 `Yii::$container->set()` 来定义。 ->>>>>>> upstream/master 例如,如果你想自定义 [[yii\widgets\LinkPager]] 小部件,以便让分页器最多只显示 5 个翻页按钮(默认是 10 个), 你可以用下述代码实现: diff --git a/docs/guide-zh-CN/concept-di-container.md b/docs/guide-zh-CN/concept-di-container.md index 7553937..3fbba38 100644 --- a/docs/guide-zh-CN/concept-di-container.md +++ b/docs/guide-zh-CN/concept-di-container.md @@ -1,5 +1,5 @@ 依赖注入容器 -============================== +========== 依赖注入(Dependency Injection,DI)容器就是一个对象,它知道怎样初始化并配置对象及其依赖的所有对象。 [Martin 的文章](http://martinfowler.com/articles/injection.html) 已经解释了 DI 容器为什么很有用。 @@ -7,13 +7,13 @@ 依赖注入 --------------------- +------- Yii 通过 [[yii\di\Container]] 类提供 DI 容器特性。 它支持如下几种类型的依赖注入: * 构造方法注入; -* Method injection; +* 方法注入; * Setter 和属性注入; * PHP 回调注入. @@ -40,13 +40,13 @@ $foo = new Foo($bar); ``` -### Method Injection +### 方法注入 -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 -and passing it to the constructor may not be possible or may cause too much overhead in the majority of use cases. +通常,类的依赖关系传递给构造函数,并且在整个生命周期中都可以在类内部使用。 +通过方法注入,可以提供仅由类的单个方法需要的依赖关系, +并将其传递给构造函数可能不可行,或者可能会在大多数用例中导致太多开销。 -A class method can be defined like the `doSomething()` method in the following example: +类方法可以像下面例子中的 `doSomething()` 方法一样定义: ```php class MyClass extends \yii\base\Component @@ -63,7 +63,7 @@ class MyClass extends \yii\base\Component } ``` -You may call that method either by passing an instance of `\my\heavy\Dependency` yourself or using [[yii\di\Container::invoke()]] like the following: +你可以自己通过一个实例 `\my\heavy\Dependency` 调用这个方法或使用 [[yii\di\Container::invoke()]] 如下: ```php $obj = new MyClass(/*...*/); @@ -103,18 +103,18 @@ $container->get('Foo', [], [ ]); ``` -> 信息:The [[yii\di\Container::get()]] method takes its third parameter as a configuration array that should - be applied to the object being created. If the class implements the [[yii\base\Configurable]] interface (e.g. - [[yii\base\BaseObject]]), the configuration array will be passed as the last parameter to the class constructor; - otherwise, the configuration will be applied *after* the object is created. +> Info: [[yii\di\Container::get()]] 方法将其第三个参数作为配置数组应用于正在创建的对象。 + 如果该类实现 [[yii\base\Configurable]] 接口(例如 + [[yii\base\BaseObject]]),则配置数组将作为最后一个参数传递给类构造函数; + 否则,将在创建对象*后*应用该配置。 ### PHP 回调注入 -In this case, the container will use a registered PHP callable to build new instances of a class. -Each time when [[yii\di\Container::get()]] is called, the corresponding callable will be invoked. -The callable is responsible to resolve the dependencies and inject them appropriately to the newly -created objects. For example, +在这种情况下,容器将使用已注册的 PHP 回调来构建类的新实例。 +每次调用 [[yii\di\Container::get()]] ,相应的回调将被调用。 +调用方负责解析依赖项,并适当地将它们注入到新创建的对象中。 +例如, ```php $container->set('Foo', function () { @@ -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` 类的人不再需要知道它是如何构建的。 注册依赖关系 @@ -336,9 +336,9 @@ echo \yii\widgets\LinkPager::widget(); echo \yii\widgets\LinkPager::widget(['maxButtonCount' => 20]); ``` -> Note: Properties given in the widget call will always override the definition in the DI container. -> Even if you specify an array, e.g. `'options' => ['id' => 'mypager']` these will not be merged -> with other options but replace them. +> Note: 在部件调用中给出的属性将始终覆盖DI容器中的定义。 +> 即使您指定了一个数组,例如 `'options' => ['id' => 'mypager']` 这些将不会与其他选项合并, +> 而是替换它们。 另一个例子是借用 DI 容器中自动构造方法注入带来的好处。 假设你的控制器类依赖一些其他对象,例如一个旅馆预订服务。 @@ -372,10 +372,10 @@ class HotelController extends Controller 现在如果你再次访问这个控制器,一个 `app\components\BookingService` 的实例就会被创建并被作为第三个参数注入到控制器的构造器中。 -Advanced Practical Usage ---------------- +高级实用性 +--------- -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([ @@ -431,7 +431,7 @@ $reader = $container->get('app\storage\DocumentsReader); // Will create DocumentReader object with its dependencies as described in the config ``` -> Tip: Container may be configured in declarative style using application configuration since version 2.0.11. +> Tip: Container may be configured in declarative style using application configuration since version 2.0.11. Check out the [Application Configurations](concept-configurations.md#application-configurations) subsection of the [Configurations](concept-configurations.md) guide article. @@ -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([ @@ -469,21 +469,21 @@ $reader = $container->get('app\storage\DocumentsReader); // Will behave exactly the same as in the previous example. ``` -You might notice `Instance::of('tempFileStorage')` notation. It means, that the [[yii\di\Container|Container]] -will implicitly provide a dependency registered with the name of `tempFileStorage` and pass it as the first argument -of `app\storage\DocumentsWriter` constructor. +你可能会注意到 `Instance::of('tempFileStorage')` 符号。这意味着,[[yii\di\Container|Container]] +将隐含地提供一个用 `tempFileStorage` 名称注册的依赖项, +并将其作为 `app\storage\DocumentsWriter` 构造函数的第一个参数传递。 -> Note: [[yii\di\Container::setDefinitions()|setDefinitions()]] and [[yii\di\Container::setSingletons()|setSingletons()]] - methods are available since version 2.0.11. +> Note: [[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. -Some classes do not change the state during runtime, therefore they may be registered as singletons -in order to increase the application performance. +配置优化的另一个步骤是将某些依赖项注册为单例。 +通过 [[yii\di\Container::set()|set()]] 注册的依赖项将在每次需要时实例化。 +某些类在运行时不会更改状态, +因此它们可能会被注册为单例以提高应用程序的性能。 -A good example could be `app\storage\FileStorage` class, that executes some operations on file system with a simple -API (e.g. `$fs->read()`, `$fs->write()`). These operations do not change the internal class state, so we can -create its instance once and use it multiple times. +一个很好的例子可以是 `app\storage\FileStorage` 类,它用一个简单的 API +(例如 `$fs->read()`,`$fs->write()`)在文件系统上执行一些操作。 +这些操作不会更改内部类的状态,因此我们可以创建一次实例并多次使用它。 ```php $container->setSingletons([ @@ -532,5 +532,3 @@ Yii 在依赖住入(DI)容器之上实现了它的[服务定位器](concept- 当一个服务定位器尝试创建一个新的对象实例时,它会把调用转发到 DI 容器。 后者将会像前文所述那样自动解决依赖关系。 - - diff --git a/docs/guide-zh-CN/concept-properties.md b/docs/guide-zh-CN/concept-properties.md index 4c3c5ba..6695aec 100644 --- a/docs/guide-zh-CN/concept-properties.md +++ b/docs/guide-zh-CN/concept-properties.md @@ -20,7 +20,7 @@ $object->label = trim($label); 它支持基于类内的 **getter** 和 **setter**(读取器和设定器)方法来定义属性。 如果某类需要支持这个特性,只需要继承 [[yii\base\Object]] 或其子类即可。 -> 信息:几乎每个 Yii 框架的核心类都继承自 [[yii\base\Object]] 或其子类。 +> Info: 几乎每个 Yii 框架的核心类都继承自 [[yii\base\Object]] 或其子类。 这意味着只要在核心类中见到 getter 或 setter 方法,就可以像调用属性一样调用它。 getter 方法是名称以 `get` 开头的方法,而 setter 方法名以 `set` 开头。 diff --git a/docs/guide-zh-CN/db-active-record.md b/docs/guide-zh-CN/db-active-record.md index 9bcc88f..dffa5de 100644 --- a/docs/guide-zh-CN/db-active-record.md +++ b/docs/guide-zh-CN/db-active-record.md @@ -488,7 +488,7 @@ $customer->loadDefaultValues(); 值绑定到具有正确类型的。但是,ActiveRecord 实例的属性值不会 在保存过程中转换。 -> Tip: 你可以使用 [[yii\behaviors\AttributeTypecastBehavior]] 来简化属性的类型转换 +> Tip: 你可以使用 [[yii\behaviors\AttributeTypecastBehavior]] 来简化属性的类型转换 在 ActiveRecord 验证或者保存过程中。 diff --git a/docs/guide-zh-CN/db-dao.md b/docs/guide-zh-CN/db-dao.md index 7847218..25d0747 100644 --- a/docs/guide-zh-CN/db-dao.md +++ b/docs/guide-zh-CN/db-dao.md @@ -95,7 +95,7 @@ return [ 你常常需要配置 [[yii\db\Connection::username|username]] 和 [[yii\db\Connection::password|password]]。 请参考 [[yii\db\Connection]] 来获取完整的可配置属性列表。 -> 信息:当你实例化一个 DB Connection 时, +> Info: 当你实例化一个 DB Connection 时, 直到你第一次执行 SQL 或者你明确地调用 [[yii\db\Connection::open()|open()]] 方法时, 才建立起实际的数据库连接。 @@ -535,7 +535,7 @@ $rows = Yii::$app->db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); Yii::$app->db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute(); ``` -> 信息:通过调用 [[yii\db\Command::execute()]] 来执行的语句都被视为写操作, +> Info: 通过调用 [[yii\db\Command::execute()]] 来执行的语句都被视为写操作, 而其他所有通过调用 [[yii\db\Command]] 中任一 "query" 方法来执行的语句都被视为读操作。 你可以通过 `Yii::$app->db->slave` 来获取当前有效的从库连接。 @@ -550,7 +550,7 @@ Yii::$app->db->createCommand("UPDATE user SET username='demo' WHERE id=1")->exec 一个“挂掉的”服务器将会被记住, 因此,在一个 yii\db\Connection::serverRetryInterval 内将不再试着连接该服务器。 -> 信息:在上面的配置中, +> Info: 在上面的配置中, 每个从库都共同地指定了 10 秒的连接超时时间, 这意味着,如果一个从库在 10 秒内不能被连接上, 它将被视为“挂掉的”。 @@ -604,7 +604,7 @@ Yii::$app->db->createCommand("UPDATE user SET username='demo' WHERE id=1")->exec 唯一的差别是, 如果没有主库可用,将抛出一个异常。 -> Note: 当你使用 [[yii\db\Connection::masters|masters]] 属性来配置一个或多个主库时, +> Note: 当你使用 [[yii\db\Connection::masters|masters]] 属性来配置一个或多个主库时, 所有其他指定数据库连接的属性 (例如 `dsn`, `username`, `password`) 与 `Connection` 对象本身将被忽略。 默认情况下, diff --git a/docs/guide-zh-CN/db-migrations.md b/docs/guide-zh-CN/db-migrations.md index 7ad7455..c3ed741 100644 --- a/docs/guide-zh-CN/db-migrations.md +++ b/docs/guide-zh-CN/db-migrations.md @@ -149,7 +149,7 @@ migration 的基类 [[yii\db\Migration]] 通过 [[yii\db\Migration::db|db]] 属 在使用抽象类型的时候,你可以添加额外的约束条件。在上面的例子当中, `NOT NULL` 被添加到 `Schema::TYPE_STRING` 当中来指定该字段不能为空。 -> Tip: 抽象类型和实体类型之间的映射关系是由每个具体的 `QueryBuilder` +> Tip: 抽象类型和实体类型之间的映射关系是由每个具体的 `QueryBuilder` 类当中的 [[yii\db\QueryBuilder::$typeMap|$typeMap]] 属性所指定的。 Since version 2.0.6, you can make use of the newly introduced schema builder which provides more convenient way of defining column schema. @@ -919,7 +919,7 @@ class m150101_185401_create_news_table extends Migration 如果有多个迁移都使用到了同一个数据库,那么建议你创建一个迁移的基类,里面包含上述的 `init()` 代码。 然后每个迁移类都继承这个基类就可以了。 -> Tip: 除了在 [[yii\db\Migration::db|db]] 参数当中进行设置以外, +> Tip: 除了在 [[yii\db\Migration::db|db]] 参数当中进行设置以外, 你还可以通过在迁移类中创建新的数据库连接来操作不同的数据库。 然后通过这些连接再使用 [DAO 方法](db-dao.md) 来操作不同的数据库。 @@ -934,3 +934,4 @@ yii migrate --migrationPath=@app/migrations/db2 --db=db2 第一条命令将会把 `@app/migrations/db1` 目录下的迁移提交到 `db1` 数据库当中, 第二条命令则会把 `@app/migrations/db2` 下的迁移提交到 `db2` 数据库当中,以此类推。 + diff --git a/docs/guide-zh-CN/documentation_style_guide.md b/docs/guide-zh-CN/documentation_style_guide.md new file mode 100644 index 0000000..fd0058b --- /dev/null +++ b/docs/guide-zh-CN/documentation_style_guide.md @@ -0,0 +1,87 @@ +# Yii 文档风格指南 + +编写或编辑任何 Yii 文档时的准则。 + +*此文还需要扩展。* + +## 总体风格 + +* 尽量使用主动语态。 +* 使用简短的陈述性句子。 +* 尽可能使用代码展示想法。 +* 请勿使用“我们”。这指的是 Yii 开发团队或 Yii 核心团队。更好的是从框架或指南的角度来考虑。 +* 使用牛津逗号(例如,“这个,那个,另一个”不是“这个,那个和另一个”)。 + +## 格式 + +* 使用 *斜体* 强调,不要大写,粗体或下划线。 + +## 列表 + +* 数字列表应该是以句号结尾的完整句子。 +* 项目符号列表应该是以分号结尾的片段,除了最后一个项目,它应该以句点结尾。 + +## 块 + +块使用 Markdown 语法 `> Type: `。有四种块类型: + +* `Warning`, 对于不安全的事情和其他问题 +* `Note`, 强调关键概念,需要避免的事情 +* `Info`, 一般资料(旁白); 不如“注意”表达强烈 +* `Tip`, 专业提示,附加提示,可能是有用的,但可能并非每个人都需要 + +冒号后的句子应以大写字母开头。 + +在翻译文档时,不应翻译这些 Block 标示符。 +将它们保持原样并仅翻译块内容。 +为了翻译 `Type` 这些词,每个指南翻译应该有一个 `blocktypes.json` 文件 +并包含翻译。以下显示了德语的一个示例: + +```json +{ + "Warning:": "Achtung:", + "Note:": "Hinweis:", + "Info:": "Info:", + "Tip:": "Tipp:" +} +``` + +## 参考 + +* Yii 2.0 或 Yii 2(不能是 Yii2 或 Yii2.0)。 +* 指南的每个“页面”都被称为“章节”。 +* 代码对象的引用: + - 请参阅使用完整的命名空间类:`yii\base\Model` + - 即使它们不是静态的,也可以使用静态语法引用类属性:`yii\base\Model::$validators` + - 即使它们不是静态的,也可以使用静态语法来引用类方法,并且使用括号来表示它是一种方法:`yii\base\Model::validate()` + - 对代码对象的引用应该写在 `[[]]` 中以生成指向API文档的链接。 例如,`[[yii\base\Model]]`,`[[yii\base\Model::$validators]]`,或 `[[yii\base\Model::validate()]]`。 + +## 字母大小写 + +* Web,不是 web +* guide,不是 Guide + +## 验证文档 + +以下脚本可帮助查找指南中的链接和其他问题: + +查找无效的链接(可能会出现一些误报): + + grep -rniP "\[\[[^\],']+?\][^\]]" docs/guide* + grep -rniP "[^\[]\[[^\]\[,']+?\]\]" docs/guide* + +## 译者的归属 + +翻译人员的姓名将在翻译版本的 +指南的作者中列出。 +因此,在每个指南目录中使用与英语不同的语言时,应创建一个“translators.json”文件, +其中包含参与翻译的人员的名称数组。 + +```json +[ + "Jane Doe", + "John Doe" +] +``` + +如果您对翻译有重要贡献,请随时发送 pull request 并添加您的名字。 \ No newline at end of file diff --git a/docs/guide-zh-CN/helper-html.md b/docs/guide-zh-CN/helper-html.md index 960be17..e61374d 100644 --- a/docs/guide-zh-CN/helper-html.md +++ b/docs/guide-zh-CN/helper-html.md @@ -166,7 +166,7 @@ $decodedUserName = Html::decode($userName); 处理表单标签是大量的重复性劳动并且易错。因此, Yii 也提供了一系列的方法来辅助处理表单标签。 -> Note: 考虑在处理 models 以及需要验证的情形下,使用 [[yii\widgets\ActiveForm|ActiveForm]] 组件。 +> Note: 考虑在处理 models 以及需要验证的情形下,使用 [[yii\widgets\ActiveForm|ActiveForm]] 组件。 ### 创建表单 diff --git a/docs/guide-zh-CN/input-forms.md b/docs/guide-zh-CN/input-forms.md index 81872b1..c9641d8 100644 --- a/docs/guide-zh-CN/input-forms.md +++ b/docs/guide-zh-CN/input-forms.md @@ -116,7 +116,7 @@ echo $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Ite [[yii\helpers\Html::submitButton()|Html::submitButton()]]。 -> Tip: 如果你正在你的应用程序中使用 Twitter Bootstrap CSS 你可以使用[[yii\bootstrap\ActiveForm]] +> Tip: 如果你正在你的应用程序中使用 Twitter Bootstrap CSS 你可以使用[[yii\bootstrap\ActiveForm]] > 来代替 [[yii\widgets\ActiveForm]]。 > 前者继承自后者并在生成表单字段时使用 Bootstrap 特有的样式。 diff --git a/docs/guide-zh-CN/input-validation.md b/docs/guide-zh-CN/input-validation.md index bd1d749..6d9e21c 100644 --- a/docs/guide-zh-CN/input-validation.md +++ b/docs/guide-zh-CN/input-validation.md @@ -462,7 +462,7 @@ class EntryForm extends Model 因为,它可以让用户更快速的得到错误信息,也因此可以提供更好的用户体验。 你可以使用或自己实现除服务器端验证之外,**还能额外**客户端验证功能的验证器。 -> 信息:尽管客户端验证为加分项,但它不是必须项。它存在的主要意义在于给用户提供更好的客户体验。 +> Info: 尽管客户端验证为加分项,但它不是必须项。它存在的主要意义在于给用户提供更好的客户体验。 正如“永远不要相信来自终端用户的输入信息”,也同样永远不要相信客户端验证。基于这个理由, 你应该始终如前文所描述的那样,通过调用 [[yii\base\Model::validate()]] 方法执行服务器端验证。 @@ -722,7 +722,7 @@ if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { The above code will check whether the current request is an AJAX. If yes, it will respond to this request by running the validation and returning the errors in JSON format. -> 信息:You can also use [Deferred Validation](#deferred-validation) to perform AJAX validation. +> Info: You can also use [Deferred Validation](#deferred-validation) to perform AJAX validation. However, the AJAX validation feature described here is more systematic and requires less coding effort. When both `enableClientValidation` and `enableAjaxValidation` are set to true, AJAX validation request will be triggered diff --git a/docs/guide-zh-CN/intro-upgrade-from-v1.md b/docs/guide-zh-CN/intro-upgrade-from-v1.md index e5c9772..7b9c6d3 100644 --- a/docs/guide-zh-CN/intro-upgrade-from-v1.md +++ b/docs/guide-zh-CN/intro-upgrade-from-v1.md @@ -13,7 +13,7 @@ 安装 ------------- +--- Yii 2.0 完全拥抱 [Composer](https://getcomposer.org/),它是事实上的 PHP 依赖管理工具。 核心框架以及扩展的安装都通过 Composer 来处理。想要了解更多如何安装 Yii 2.0 请参阅本指南的 @@ -23,7 +23,7 @@ Yii 2.0 完全拥抱 [Composer](https://getcomposer.org/),它是事实上的 P PHP 需求 ----------------- +------- Yii 2.0 需要 PHP 5.4 或更高版本,该版本相对于 Yii 1.1 所需求的 PHP 5.2 而言有巨大的改进。 因此在语言层面上有很多的值得注意的不同之处。 @@ -54,7 +54,7 @@ Yii 2.0 里最明显的改动就数命名空间的使用了。几乎每一个核 组件(Component)与对象(BaseObject) --------------------- +--------------------------------- Yii 2.0 把 1.1 中的 `CComponent` 类拆分成了两个类:[[yii\base\Object]] 和 [[yii\base\Component]]。 [[yii\base\Object|Object]] 类是一个轻量级的基类,你可以通过 getters 和 setters 来定义[对象的属性](concept-properties.md)。 @@ -67,7 +67,7 @@ Yii 2.0 把 1.1 中的 `CComponent` 类拆分成了两个类:[[yii\base\Object 对象的配置 --------------------- +--------- [[yii\base\Object|Object]] 类引入了一种统一对象配置的方法。 所有 [[yii\base\Object|Object]] 的子类都应该用以下方法声明它的构造方法(如果需要的话), @@ -112,7 +112,7 @@ $object = Yii::createObject([ 事件(Event) ------- +----------- 在 Yii 1 中,通常通过定义 `on` 开头的方法(例如 `onBeforeSave`)来创建事件。 而在 Yii 2 中,你可以使用任意的事件名了。同时通过调用 [[yii\base\Component::trigger()|trigger()]] 方法来触发相关事件: @@ -153,7 +153,7 @@ Yii 2.0 将路径别名的应用扩大至文件/目录路径和 URL。Yii 2.0 视图(View) ------ +---------- Yii 2 中视图最明显的改动是视图内的特殊变量 `$this` 不再指向当前控制器或小部件, 而是指向**视图**对象,它是 2.0 中引入的全新概念。**视图**对象为 [[yii\web\View]] 的实例, @@ -175,7 +175,7 @@ echo $this->render('_item', ['item' => $item]); 模型(Model) ------- +----------- Yii 2.0 使用 [[yii\base\Model]] 作为模型基类,类似于 1.1 的 `CModel` 。 `CFormModel` 被完全弃用了,现在要创建表单模型类,可以通过继承 [[yii\base\Model]] 类来实现。 @@ -231,7 +231,7 @@ public function actionView($id) 小部件(Widget) -------- +------------- Yii 2.0 使用 [[yii\base\Widget]] 作为小部件基类,类似于 1.1 的 `CWidget`。 @@ -259,7 +259,7 @@ ActiveForm::end(); 主题(Theme) ------- +----------- 2.0 主题的运作方式跟以往完全不同了。它们现在基于**路径映射机制**,该机制会把一个源视图文件的路径映射到一个主题视图文件路径。 举例来说,如果路径映射为 `['/web/views' => '/web/themes/basic']`, @@ -274,7 +274,7 @@ ActiveForm::end(); 控制台应用(Console Application) --------------------- +------------------------------ 控制台应用现在如普通的 Web 应用程序一样,由控制器组成, 控制台的控制器继承自 [[yii\console\Controller]],类似于 1.1 的 `CConsoleCommand`。 @@ -290,7 +290,7 @@ Yii 2.0 支持基于代码注释自动生成相的关命令行帮助(help) 国际化(I18N) ----- +------------ Yii 2.0 移除了原来内置的日期格式器和数字格式器,为了支持 [PECL intl PHP module](http://pecl.php.net/package/intl)(PHP 的国际化扩展)的使用。 @@ -302,7 +302,7 @@ Yii 2.0 移除了原来内置的日期格式器和数字格式器,为了支持 动作过滤器(Action Filters) --------------- +------------------------- 操作的过滤现在通过行为(behavior)来实现。要定义一个新的,自定义的过滤器,请继承 [[yii\base\ActionFilter]] 类。 要使用一个过滤器,需要把过滤器类作为一个 `behavior` 绑定到控制器上。 @@ -326,7 +326,7 @@ public function behaviors() 前端资源(Assets) ------- +--------------- Yii 2.0 引入了一个新的概念,称为**资源包**(Asset Bundle),以代替 1.1 的脚本包概念。 @@ -340,7 +340,7 @@ Yii 2.0 引入了一个新的概念,称为**资源包**(Asset Bundle), 助手类(Helpers) -------- +--------------- Yii 2.0 很多常用的静态助手类,包括: @@ -352,8 +352,8 @@ Yii 2.0 很多常用的静态助手类,包括: 请参考[助手一览](helper-overview.md) 章节来了解更多。 -表单 ------ +表单(Forms) +----------- Yii 2.0 引进了**表单栏(field)**的概念,用来创建一个基于 [[yii\widgets\ActiveForm]] 的表单。 一个表单栏是一个由标签、输入框、错误消息(可能还有提示文字)组成的容器, @@ -374,7 +374,7 @@ Yii 2.0 引进了**表单栏(field)**的概念,用来创建一个基于 [[ 查询生成器(Query Builder) -------------- +------------------------ Yii 1.1 中,查询语句的生成分散在多个类中,包括 `CDbCommand`,`CDbCriteria` 以及 `CDbCommandBuilder`。 Yii 2.0 以 [[yii\db\Query|Query]] 对象的形式表示一个数据库查询, @@ -398,7 +398,7 @@ $rows = $command->queryAll(); 活动记录(Active Record) -------------- +---------------------- Yii 2.0 的[活动记录](db-active-record.md)改动了很多。 两个最显而易见的改动分别涉及查询语句的生成(query building)和关联查询的处理(relational query handling)。 @@ -434,6 +434,7 @@ class Customer extends \yii\db\ActiveRecord ```php $orders = $customer->getOrders()->andWhere('status=1')->all(); ``` + 当贪婪加载一段关联关系时,Yii 2.0 和 1.1 的运作机理并不相同。 具体来说,在 1.1 中使用一条 JOIN 语句同时查询主表和关联表记录。 在 Yii 2.0 中会使用两个没有 JOIN 的 SQL 语句:第一条语句取回主表记录, @@ -525,10 +526,10 @@ Yii 2.0 的 URL 管理跟 1.1 中很像。一个主要的改进是现在的 URL 请参考[URL 解析和生成](runtime-url-handling.md) 章节,以了解更多细节。. -An important change in the naming convention for routes is that camel case names of controllers -and actions are now converted to lower case where each word is separated by a hypen, e.g. the controller -id for the `CamelCaseController` will be `camel-case`. -See the section about [controller IDs](structure-controllers.md#controller-ids) and [action IDs](structure-controllers.md#action-ids) for more details. +一个重要变化是路由命名的约定, +现在的控制器和动作的驼峰命名会被转换成小写字母, +其中每个单词由一个专有的连字号分隔,例如,`CamelCaseController` 将为 `camel-case`。 +有关更多详细信息,请参阅关于 [controller IDs](structure-controllers.md#controller-ids) 和 [action IDs](structure-controllers.md#action-ids) 的部分。 同时使用 Yii 1.1 和 2.x diff --git a/docs/guide-zh-CN/output-data-widgets.md b/docs/guide-zh-CN/output-data-widgets.md index 3654087..aa0e78d 100644 --- a/docs/guide-zh-CN/output-data-widgets.md +++ b/docs/guide-zh-CN/output-data-widgets.md @@ -557,7 +557,7 @@ public function rules() $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name')]); ``` -> 信息:在上面的代码中,我们使用相同的字符串作为关联名称和表别名; +> Info: 在上面的代码中,我们使用相同的字符串作为关联名称和表别名; > 然而,当你的表别名和关联名称不相同的时候,你得注意在哪使用你的别名,在哪使用你的关联名称。 > 一个简单的规则是在每个构建数据库查询的地方使用别名,而在所有其他和定义相关的诸如: >`attributes()` 和 `rules()` 等地方使用关联名称。 @@ -592,7 +592,7 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name' > $dataProvider->sort->defaultOrder = ['author.name' => SORT_ASC]; > ``` -> 信息:更多关于 `joinWith` 和在后台执行查询的相关信息, +> Info: 更多关于 `joinWith` 和在后台执行查询的相关信息, > 可以查看 [active record docs on joining with relations](db-active-record.md#joining-with-relations)。 #### SQL视图用于过滤、排序和显示数据 diff --git a/docs/guide-zh-CN/output-formatting.md b/docs/guide-zh-CN/output-formatting.md index 7da0840..6eb1735 100644 --- a/docs/guide-zh-CN/output-formatting.md +++ b/docs/guide-zh-CN/output-formatting.md @@ -40,7 +40,7 @@ echo Yii::$app->formatter->format('2014-01-01', 'date'); echo Yii::$app->formatter->format(0.125, ['percent', 2]); ``` -> Note: `formatter` 组件用来格式化最终展示给用户的数据. +> Note: `formatter` 组件用来格式化最终展示给用户的数据。 > 如果你想要将用户的输入进行格式化或者只是将一些别的日期数据进行格式化(这里的格式化说的是机器可读的格式化),不要使用这个组件, > 而应该使用 [[yii\validators\DateValidator]] 和 [[yii\validators\NumberValidator]] 进行用户输入格式化 > 关于日期格式化,戳这里 [date()](http://php.net/manual/en/function.date.php) diff --git a/docs/guide-zh-CN/output-theming.md b/docs/guide-zh-CN/output-theming.md index ed3de40..90737a4 100644 --- a/docs/guide-zh-CN/output-theming.md +++ b/docs/guide-zh-CN/output-theming.md @@ -33,7 +33,7 @@ return [ ]; ``` -> 信息:主题支持路径别名。当我们在做视图替换的时候, +> Info: 主题支持路径别名。当我们在做视图替换的时候, 路径别名将被转换成实际的文件路径或者URL。 你可以通过 [[yii\base\View::theme]] 属性访问 [[yii\base\Theme]] 对象。例如,在一个视图文件里,你可以写下面的代码, diff --git a/docs/guide-zh-CN/rest-quick-start.md b/docs/guide-zh-CN/rest-quick-start.md index 44b4121..a085b8e 100644 --- a/docs/guide-zh-CN/rest-quick-start.md +++ b/docs/guide-zh-CN/rest-quick-start.md @@ -77,7 +77,7 @@ class UserController extends ActiveController ] ``` -> 信息:上述配置是可选的。若未按上述配置,API 将仅可以分辨 +> Info: 上述配置是可选的。若未按上述配置,API 将仅可以分辨 `application/x-www-form-urlencoded` 和 `multipart/form-data` 输入格式。 @@ -183,7 +183,7 @@ Content-Type: application/json; charset=UTF-8 例如:URL `http://localhost/users?fields=id,email` 将只返回 `id` 和 `email` 字段。 -> 信息:你可能已经注意到了 `http://localhost/users` 的结果包括一些敏感字段, +> Info: 你可能已经注意到了 `http://localhost/users` 的结果包括一些敏感字段, > 例如 `password_hash`, `auth_key` 你肯定不希望这些出现在你的 API 结果中。 > 你应该在 [响应格式](rest-response-formatting.md) 部分中过滤掉这些字段。 diff --git a/docs/guide-zh-CN/rest-routing.md b/docs/guide-zh-CN/rest-routing.md index 872d9f4..47707e3 100644 --- a/docs/guide-zh-CN/rest-routing.md +++ b/docs/guide-zh-CN/rest-routing.md @@ -77,7 +77,7 @@ 这是因为 [[yii\rest\UrlRule]] 能够为他们使用的末端全自动复数化控制器 ID。 您可以通过设置 [[yii\rest\UrlRule::pluralize]] 为 false 来禁用此行为。 -> 信息:控制器的 ID 复数化由 [[yii\helpers\Inflector::pluralize()]] 完成。该方法遵循 +> Info: 控制器的 ID 复数化由 [[yii\helpers\Inflector::pluralize()]] 完成。该方法遵循 特定的规则. 举个例子, 单词 `box` 会被复数化为 `boxes` 而不是 `boxs`。 如果自动复数化不能满足你的需求,你也可以配置 diff --git a/docs/guide-zh-CN/rest-versioning.md b/docs/guide-zh-CN/rest-versioning.md index 8958a75..2e3486d 100644 --- a/docs/guide-zh-CN/rest-versioning.md +++ b/docs/guide-zh-CN/rest-versioning.md @@ -5,7 +5,7 @@ 代码,APIs 是为了给超出控制的客户端使用。因此, 应该尽可能的保持向后兼容性,如果有一些变化不能向后兼容,你应该在新版本的 API 中采用它同时增加版本号。现有客户端可以继续使用旧版本的API;新的或升级的客户端可以在新的API版本中获得新的功能。 -> Tip: 可以参考 [Semantic Versioning](http://semver.org/) +> Tip: 可以参考 [Semantic Versioning](http://semver.org/) 来获取更多关于设计 API 版本号的信息 关于如何实现 API 版本,一个常见的做法是在 API 的 URL 中嵌入版本号。例如, diff --git a/docs/guide-zh-CN/runtime-handling-errors.md b/docs/guide-zh-CN/runtime-handling-errors.md index 2780eff..9f6ff07 100644 --- a/docs/guide-zh-CN/runtime-handling-errors.md +++ b/docs/guide-zh-CN/runtime-handling-errors.md @@ -66,7 +66,7 @@ throw new NotFoundHttpException(); 错误处理器会显示异常以及详细的函数调用栈和源代码行数来帮助调试, 当`YII_DEBUG` 为 false,只有错误信息会被显示以防止应用的敏感信息泄漏。 -> 信息:如果异常是继承 [[yii\base\UserException]], +> Info: 如果异常是继承 [[yii\base\UserException]], 不管`YII_DEBUG`为何值,函数调用栈信息都不会显示, 这是因为这种错误会被认为是用户产生的错误,开发人员不需要去修正。 diff --git a/docs/guide-zh-CN/runtime-requests.md b/docs/guide-zh-CN/runtime-requests.md index c893b4c..a5d230f 100644 --- a/docs/guide-zh-CN/runtime-requests.md +++ b/docs/guide-zh-CN/runtime-requests.md @@ -34,7 +34,7 @@ $name = $request->post('name', ''); // 等价于: $name = isset($_POST['name']) ? $_POST['name'] : ''; ``` -> 信息:建议你像上面那样通过 `request` 组件来获取请求参数,而不是 +> Info: 建议你像上面那样通过 `request` 组件来获取请求参数,而不是 直接访问 `$_GET` 和 `$_POST`。 这使你更容易编写测试用例,因为你可以伪造数据来创建一个模拟请求组件。 @@ -52,7 +52,7 @@ $params = $request->bodyParams; $param = $request->getBodyParam('id'); ``` -> 信息:不同于 `GET` 参数,`POST`,`PUT`,`PATCH` 等等这些提交上来的参数是在请求体中被发送的。 +> Info: 不同于 `GET` 参数,`POST`,`PUT`,`PATCH` 等等这些提交上来的参数是在请求体中被发送的。 当你通过上面介绍的方法访问这些参数的时候,`request` 组件会解析这些参数。 你可以通过配置 [[yii\web\Request::parsers]] 属性来自定义怎样解析这些参数。 @@ -123,7 +123,7 @@ if ($headers->has('User-Agent')) { /* 这是一个 User-Agent 头 */ } 这个方法通过 [[yii\web\Request::acceptableLanguages|acceptableLanguages]] 在你的应用中所支持的语言列表里进行比较筛选,返回最适合的语言。 -> Tip: 你也可以使用 [[yii\filters\ContentNegotiator|ContentNegotiator]] +> Tip: 你也可以使用 [[yii\filters\ContentNegotiator|ContentNegotiator]] 过滤器进行动态确定哪些内容类型和语言应该在响应中使用。 这个过滤器实现了上面介绍的内容协商的属性和方法。 diff --git a/docs/guide-zh-CN/runtime-responses.md b/docs/guide-zh-CN/runtime-responses.md index b29f550..76c0247 100644 --- a/docs/guide-zh-CN/runtime-responses.md +++ b/docs/guide-zh-CN/runtime-responses.md @@ -73,7 +73,7 @@ $headers->set('Pragma', 'no-cache'); $values = $headers->remove('Pragma'); ``` -> 信息:头名称是大小写敏感的,在[[yii\web\Response::send()]]方法 +> Info: 头名称是大小写敏感的,在[[yii\web\Response::send()]]方法 调用前新注册的头信息并不会发送给用户。 @@ -183,7 +183,7 @@ public function actionOld() \Yii::$app->response->redirect('http://example.com/new', 301)->send(); ``` -> 信息:[[yii\web\Response::redirect()]] 方法默认会设置响应状态码为302,该状态码会告诉浏览器请求的资源 +> Info: [[yii\web\Response::redirect()]] 方法默认会设置响应状态码为302,该状态码会告诉浏览器请求的资源 *临时* 放在另一个URI地址上,可传递一个301状态码告知浏览器请求 的资源已经 *永久* 重定向到新的URId地址。 @@ -193,7 +193,7 @@ public function actionOld() 在客户端可编写JavaScript 代码读取该头部值然后让浏览器跳转对应的URL。 -> 信息:Yii 配备了一个`yii.js` JavaScript 文件提供常用JavaScript功能, +> Info: Yii 配备了一个`yii.js` JavaScript 文件提供常用JavaScript功能, 包括基于`X-Redirect`头的浏览器跳转, 因此,如果你使用该JavaScript 文件(通过[[yii\web\YiiAsset]] 资源包注册), 就不需要编写AJAX跳转的代码。 diff --git a/docs/guide-zh-CN/runtime-routing.md b/docs/guide-zh-CN/runtime-routing.md index d158a5c..5e62aec 100644 --- a/docs/guide-zh-CN/runtime-routing.md +++ b/docs/guide-zh-CN/runtime-routing.md @@ -3,7 +3,7 @@ 当[入口脚本](structure-entry-scripts.md)在调用 [[yii\web\Application::run()|run()]] 方法时,它进行的第一个操作就是解析输入的请求,然后实例化对应的[控制器操作](structure-controllers.md)处理这个请求。 -该过程就被称为**引导路由(routing)**。(译注:中文里既是动词也是名词) +该过程就被称为**引导路由(routing)**。 The reverse process of routing is called *URL creation*, which creates a URL from a given route and the associated query parameters. When the created URL is later requested, the routing process can resolve it @@ -36,9 +36,12 @@ And if the created URL is requested later, it will still be parsed back into the ``` -## URL Formats +## URL 格式化 -The [[yii\web\UrlManager|URL manager]] supports two URL formats: the default URL format and the pretty URL format. +The [[yii\web\UrlManager|URL manager]] supports two URL formats: + +- the default URL format; +- the pretty URL format. The default URL format uses a query parameter named `r` to represent the route and normal query parameters to represent the query parameters associated with the route. For example, the URL `/index.php?r=post/view&id=100` represents @@ -55,10 +58,12 @@ You may switch between the two URL formats by toggling the [[yii\web\UrlManager: property of the [[yii\web\UrlManager|URL manager]] without changing any other application code. -## Routing +## 路由 + +Routing involves two steps: -Routing involves two steps. In the first step, the incoming request is parsed into a route and the associated -query parameters. In the second step, a [controller action](structure-controllers.md#actions) corresponding to the parsed route +- the incoming request is parsed into a route and the associated query parameters; +- a [controller action](structure-controllers.md#actions) corresponding to the parsed route is created to handle the request. When using the default URL format, parsing a request into a route is as simple as getting the value of a `GET` @@ -105,6 +110,12 @@ return [ ]; ``` +Similar to the default route of the application, there is also a default route for modules, so for example if there +is a `user` module and the request is parsed into the route `user` the module's [[yii\base\Module::defaultRoute|defaultRoute]] +is used to determine the controller. By default the controller name is `default`. If no action is specified in [[yii\base\Module::defaultRoute|defaultRoute]], +the [[yii\base\Controller::defaultAction|defaultAction]] property of the controller is used to determine the action. +In this example, the full route would be `user/default/index`. + ### `catchAll` 路由(全拦截路由) @@ -124,10 +135,11 @@ With the above configuration, the `site/offline` action will be used to handle a The `catchAll` property should take an array whose first element specifies a route, and the rest of the elements (name-value pairs) specify the parameters to be [bound to the action](structure-controllers.md#action-parameters). -> 信息:Debug panel on development environment will not work when this property is enabled +> Info: The [debug toolbar](https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md) in development environment +> will not work when this property is enabled. -## Creating URLs +## 创建 URLs Yii provides a helper method [[yii\helpers\Url::to()]] to create various kinds of URLs from given routes and their associated query parameters. For example, @@ -300,7 +312,7 @@ a parameter named `id`. ] ``` -> 信息:The pattern in a rule is used to match the path info part of a URL. For example, the path info of +> Info: The pattern in a rule is used to match the path info part of a URL. For example, the path info of `/index.php/post/100?source=ad` is `post/100` (the leading and ending slashes are ignored) which matches the pattern `post/(\d+)`. @@ -373,25 +385,28 @@ And when the rules are used to create URLs: ### Parameterizing Routes -You can embed parameter names in the route of a URL rule. This allows a URL rule to be used for matching multiple +You can embed parameter names in the route of a URL rule. This allows a URL rule to be used for matching multiple routes. For example, the following rules embed `controller` and `action` parameters in the routes. ```php -[ - '//' => '/', +'rules' => [ + '/create' => '/create', + '//' => '/', '/' => '/view', 's' => '/index', ] ``` -To parse a URL `/index.php/comment/100/create`, the first rule will apply, which sets the `controller` parameter to -be `comment` and `action` parameter to be `create`. The route `/` is thus resolved as `comment/create`. - -Similarly, to create a URL for the route `comment/index`, the third rule will apply, which creates a URL `/index.php/comments`. +To parse a URL `/index.php/comment/100/update`, the second rule will apply, which sets the `controller` parameter to +be `comment` and `action` parameter to be `update`. The route `/` is thus resolved as `comment/update`. + +Similarly, to create a URL for the route `comment/index`, the last rule will apply, which creates a URL `/index.php/comments`. + +> Info: By parameterizing routes, it is possible to greatly reduce the number of URL rules, which can significantly + improve the performance of [[yii\web\UrlManager|URL manager]]. + +### Default Parameter Values -> 信息:By parameterizing routes, it is possible to greatly reduce the number of URL rules, which can significantly - improve the performance of [[yii\web\UrlManager|URL manager]]. - By default, all parameters declared in a rule are required. If a requested URL does not contain a particular parameter, or if a URL is being created without a particular parameter, the rule will not apply. To make some of the parameters optional, you can configure the [[yii\web\UrlRule::defaults|defaults]] property of a rule. Parameters listed in this @@ -420,6 +435,9 @@ The above rule can be used to parse or create any of the following URLs: Without using optional parameters, you would have to create 4 rules to achieve the same result. +> Note: If [[yii\web\UrlRule::$pattern|pattern]] contains only optional parameters and slashes, first parameter could be omitted + only if all other parameters are omitted. + ### Rules with Server Names @@ -443,9 +461,12 @@ will parse the URL `http://en.example.com/posts` into the route `post/index` and ] ``` -> 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 +Since version 2.0.11, you may also use protocol relative patterns that work for both, `http` and `https`. +The syntax is the same as above but skipping the `http:` part, e.g.: `'//www.example.com/login' => 'site/login'`. + +> Note: Rules with server names should **not** include the subfolder of the entry script in their patterns. For example, if the applications entry script is at `http://www.example.com/sandbox/blog/index.php`, 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. + to be deployed under any directory without the need to change your url rules. Yii will automatically detect the base url of the application. ### URL Suffixes @@ -489,8 +510,7 @@ contains a customized URL rule which uses `.json` as its suffix instead of the g 'components' => [ 'urlManager' => [ 'enablePrettyUrl' => true, - 'showScriptName' => false, - 'enableStrictParsing' => true, + // ... 'suffix' => '.html', 'rules' => [ // ... @@ -505,60 +525,36 @@ contains a customized URL rule which uses `.json` as its suffix instead of the g ] ``` - ### HTTP Methods 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/` 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`. +be parsed into `post/update`, while a request for `GET post/100` will be parsed into `post/view`. ```php -[ - 'PUT,POST post/' => 'post/create', +'rules' => [ + 'PUT,POST post/' => 'post/update', 'DELETE post/' => 'post/delete', 'post/' => 'post/view', ] ``` -> Note: If a URL rule contains HTTP method(s) in its pattern, the rule will only be used for parsing purpose. +> Note: If a URL rule contains HTTP method(s) in its pattern, the rule will only be used for parsing purpose unless `GET` is among the specified verbs. 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. - - -### Customizing Rules + For more details, please refer to the [Routing](rest-routing.md) section in the RESTful APIs chapter. -In the previous examples, URL rules are mainly declared in terms of pattern-route pairs. This is a commonly used -shortcut format. In certain scenarios, you may want to customize a URL rule by configuring its other properties, such -as [[yii\web\UrlRule::suffix]]. This can be done by using a full configuration array to specify a rule. The following -example is extracted from the [URL Suffixes](#url-suffixes) subsection, - -```php -[ - // ...other url rules... - - [ - 'pattern' => 'posts', - 'route' => 'post/index', - 'suffix' => '.json', - ], -] -``` - -> 信息:By default if you do not specify the `class` option for a rule configuration, it will take the default - class [[yii\web\UrlRule]]. - ### Adding Rules Dynamically -URL rules can be dynamically added to the [[yii\web\UrlManager|URL manager]]. This is often needed by redistributable +URL rules can be dynamically added to the [[yii\web\UrlManager|URL manager]]. This is often needed by redistributable [modules](structure-modules.md) which want to manage their own URL rules. In order for the dynamically added rules to take effect during the routing process, you should add them during the [bootstrapping](runtime-bootstrapping.md) -stage. For modules, this means they should implement [[yii\base\BootstrapInterface]] and add the rules in the +stage of the application. For modules, this means they should implement [[yii\base\BootstrapInterface]] and add the rules in the [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] method like the following: ```php @@ -576,22 +572,23 @@ Note that you should also list these modules in [[yii\web\Application::bootstrap ### Creating Rule Classes -Despite the fact that the default [[yii\web\UrlRule]] class is flexible enough for the majority of projects, there -are situations when you have to create your own rule classes. For example, in a car dealer Web site, you may want +Despite the fact that the default [[yii\web\UrlRule]] class is flexible enough for the majority of projects, there +are situations when you have to create your own rule classes. For example, in a car dealer Web site, you may want to support the URL format like `/Manufacturer/Model`, where both `Manufacturer` and `Model` must match some data stored in a database table. The default rule class will not work here because it relies on statically declared patterns. We can create the following URL rule class to solve this problem. ```php +getPathInfo(); if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) { // check $matches[1] and $matches[3] to see - // if they match a manufacturer and a model in the database + // if they match a manufacturer and a model in the database. // If so, set $params['manufacturer'] and/or $params['model'] // and return ['car/index', $params] } - return false; // this rule does not apply + return false; // this rule does not apply } } ``` @@ -621,27 +618,76 @@ class CarUrlRule extends Object implements UrlRuleInterface And use the new rule class in the [[yii\web\UrlManager::rules]] configuration: ```php -[ +'rules' => [ // ...other rules... - [ - 'class' => 'app\components\CarUrlRule', + 'class' => 'app\components\CarUrlRule', // ...configure other properties... ], ] ``` -## Performance Consideration +## URL normalization -When developing a complex Web application, it is important to optimize URL rules so that it takes less time to parse -requests and create URLs. +Since version 2.0.10 [[yii\web\UrlManager|UrlManager]] can be configured to use [[yii\web\UrlNormalizer|UrlNormalizer]] for dealing +with variations of the same URL, for example with and without a trailing slash. Because technically `http://example.com/path` +and `http://example.com/path/` are different URLs, serving the same content for both of them can degrade SEO ranking. +By default normalizer collapses consecutive slashes, adds or removes trailing slashes depending on whether the +suffix has a trailing slash or not, and redirects to the normalized version of the URL using [permanent redirection](https://en.wikipedia.org/wiki/HTTP_301). +The normalizer can be configured globally for the URL manager or individually for each rule - by default each rule will use the normalizer +from URL manager. You can set [[yii\web\UrlRule::$normalizer|UrlRule::$normalizer]] to `false` to disable normalization +for particular URL rule. -By using parameterized routes, you may reduce the number of URL rules, which can significantly improve performance. +The following shows an example configuration for the [[yii\web\UrlNormalizer|UrlNormalizer]]: + +```php +'urlManager' => [ + 'enablePrettyUrl' => true, + 'showScriptName' => false, + 'enableStrictParsing' => true, + 'suffix' => '.html', + 'normalizer' => [ + 'class' => 'yii\web\UrlNormalizer', + // use temporary redirection instead of permanent for debugging + 'action' => UrlNormalizer::ACTION_REDIRECT_TEMPORARY, + ], + 'rules' => [ + // ...other rules... + [ + 'pattern' => 'posts', + 'route' => 'post/index', + 'suffix' => '/', + 'normalizer' => false, // disable normalizer for this rule + ], + [ + 'pattern' => 'tags', + 'route' => 'tag/index', + 'normalizer' => [ + // do not collapse consecutive slashes for this rule + 'collapseSlashes' => false, + ], + ], + ], +] +``` + +> Note: by default [[yii\web\UrlManager::$normalizer|UrlManager::$normalizer]] is disabled. You need to explicitly + configure it in order to enable URL normalization. -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. + + +## 性能考虑 + +在开发复杂的 Web 应用程序时,优化 URL 规则非常重要,以便解析请求和创建 URL 所需 +的时间更少。 + +通过使用参数化路由,您可以减少 URL 规则的数量,这可以显着提高性能。 + +当解析或创建URL时,[[yii\web\UrlManager|URL manager]] 按照它们声明的顺序检查URL规则。 +因此,您可以考虑调整URL规则的顺序,以便在较少使用的规则之前放置更具体和/或更常用的规则。 If some URL rules share the same prefix in their patterns or routes, you may consider using [[yii\web\GroupUrlRule]] so that they can be more efficiently examined by [[yii\web\UrlManager|URL manager]] as a group. This is often the case when your application is composed by modules, each having its own set of URL rules with module ID as their common prefixes. + diff --git a/docs/guide-zh-CN/runtime-sessions-cookies.md b/docs/guide-zh-CN/runtime-sessions-cookies.md index d6b1f67..0680ed4 100644 --- a/docs/guide-zh-CN/runtime-sessions-cookies.md +++ b/docs/guide-zh-CN/runtime-sessions-cookies.md @@ -69,7 +69,7 @@ foreach ($session as $name => $value) ... foreach ($_SESSION as $name => $value) ... ``` -> 信息:当使用 `session` 组件访问 session 数据时候, +> Info: 当使用 `session` 组件访问 session 数据时候, 如果 session 没有开启会自动开启, 这和通过 `$_SESSION` 不同,`$_SESSION` 要求先执行 `session_start()`。 diff --git a/docs/guide-zh-CN/start-databases.md b/docs/guide-zh-CN/start-databases.md index 8c6a284..300a0a3 100644 --- a/docs/guide-zh-CN/start-databases.md +++ b/docs/guide-zh-CN/start-databases.md @@ -74,7 +74,7 @@ return [ 上面配置的数据库连接可以在应用中通过 `Yii::$app->db` 表达式访问。 -> 信息:`config/db.php` 将被包含在应用配置文件 `config/web.php` 中, +> Info: `config/db.php` 将被包含在应用配置文件 `config/web.php` 中, 后者指定了整个[应用](structure-applications.md)如何初始化。 请参考[配置](concept-configurations.md)章节了解更多信息。 @@ -106,7 +106,7 @@ class Country extends ActiveRecord 这个 `Country` 类继承自 [[yii\db\ActiveRecord]]。你不用在里面写任何代码。 只需要像现在这样,Yii 就能根据类名去猜测对应的数据表名。 -> 信息:如果类名和数据表名不能直接对应, +> Info: 如果类名和数据表名不能直接对应, 可以覆写 [[yii\db\ActiveRecord::tableName()|tableName()]] 方法去显式指定相关表名。 使用 `Country` 类可以很容易地操作 `country` 表数据,就像这段代码: @@ -128,7 +128,7 @@ $country->name = 'U.S.A.'; $country->save(); ``` -> 信息:活动记录是面向对象、功能强大的访问和操作数据库数据的方式。你可以在[活动记录](db-active-record.md)章节了解更多信息。 +> Info: 活动记录是面向对象、功能强大的访问和操作数据库数据的方式。你可以在[活动记录](db-active-record.md)章节了解更多信息。 除此之外你还可以使用另一种更原生的被称做[数据访问对象](db-dao)的方法操作数据库数据。 diff --git a/docs/guide-zh-CN/start-forms.md b/docs/guide-zh-CN/start-forms.md index 0414dc0..446a59e 100644 --- a/docs/guide-zh-CN/start-forms.md +++ b/docs/guide-zh-CN/start-forms.md @@ -48,7 +48,7 @@ class EntryForm extends Model 该类继承自Yii 提供的一个基类 [[yii\base\Model]], 该基类通常用来表示数据。 -> 信息:[[yii\base\Model]] 被用于普通模型类的父类并与数据表**无关**。[[yii\db\ActiveRecord]] +> Info: [[yii\base\Model]] 被用于普通模型类的父类并与数据表**无关**。[[yii\db\ActiveRecord]] 通常是普通模型类的父类但与数据表有关联(译注:[[yii\db\ActiveRecord]] 类其实也是继承自 [[yii\base\Model]],增加了数据库处理)。 `EntryForm` 类包含 `name` 和 `email` 两个公共成员, @@ -119,7 +119,7 @@ class SiteController extends Controller 如果模型被成功填充数据(也就是说用户已经提交了 HTML 表单), 操作将调用 [[yii\base\Model::validate()|validate()]] 去确保用户提交的是有效数据。 -> 信息:表达式 `Yii::$app` 代表[应用](structure-applications.md)实例,它是一个全局可访问的单例。 +> Info: 表达式 `Yii::$app` 代表[应用](structure-applications.md)实例,它是一个全局可访问的单例。 同时它也是一个[服务定位器](concept-service-locator.md), 能提供 `request`,`response`,`db` 等等特定功能的组件。 在上面的代码里就是使用 `request` 组件来访问应用实例收到的 `$_POST` 数据。 @@ -228,7 +228,7 @@ http://hostname/index.php?r=site/entry field($model, 'email')->label('自定义 Email') ?> ``` -> 信息:Yii 提供了相当多类似的小部件去帮你生成复杂且动态的视图。 +> Info: Yii 提供了相当多类似的小部件去帮你生成复杂且动态的视图。 在后面你还会了解到自己写小部件是多么简单。 你可能会把自己的很多视图代码转化成小部件以提高重用,加快开发效率。 diff --git a/docs/guide-zh-CN/start-gii.md b/docs/guide-zh-CN/start-gii.md index ce1073f..1412baa 100644 --- a/docs/guide-zh-CN/start-gii.md +++ b/docs/guide-zh-CN/start-gii.md @@ -45,7 +45,7 @@ defined('YII_ENV') or define('YII_ENV', 'dev'); http://hostname/index.php?r=gii ``` -> 信息:如果你通过本机以外的机器访问 Gii,请求会被出于安全原因拒绝。 +> Info: 如果你通过本机以外的机器访问 Gii,请求会被出于安全原因拒绝。 > 你可以配置 Gii 为其添加允许访问的 IP 地址: > ```php @@ -127,7 +127,7 @@ http://hostname/index.php?r=country/index * 模型:`models/Country.php` 和 `models/CountrySearch.php` * 视图:`views/country/*.php` -> 信息:Gii 被设计成高度可定制和可扩展的代码生成工具。 +> Info: Gii 被设计成高度可定制和可扩展的代码生成工具。 使用它可以大幅提高应用开发速度。 请参考 [Gii](tool-gii.md) 章节了解更多内容。 diff --git a/docs/guide-zh-CN/start-hello.md b/docs/guide-zh-CN/start-hello.md index a8fefaf..0f576ca 100644 --- a/docs/guide-zh-CN/start-hello.md +++ b/docs/guide-zh-CN/start-hello.md @@ -22,7 +22,7 @@ 从请求中接收 `message` 参数并显示给最终用户。 如果请求没有提供 `message` 参数,操作将显示默认参数 “Hello”。 -> 信息:[操作](structure-controllers.md#creating-actions)是最终用户可以直接访问并执行的对象。 +> Info: [操作](structure-controllers.md#creating-actions)是最终用户可以直接访问并执行的对象。 操作被组织在[控制器](structure-controllers.md)中。 一个操作的执行结果就是最终用户收到的响应内容。 @@ -112,7 +112,7 @@ http://hostname/index.php?r=site/say&message=Hello+World 如果你省略 URL 中的 `message` 参数,将会看到页面只显示 “Hello”。 这是因为 `message` 被作为一个参数传给 `actionSay()` 方法,当省略它时,参数将使用默认的 `“Hello”` 代替。 -> 信息:新页面和其它页面使用同样的头部和尾部是因为 [[yii\web\Controller::render()|render()]] +> Info: 新页面和其它页面使用同样的头部和尾部是因为 [[yii\web\Controller::render()|render()]] 方法会自动把 `say` 视图执行的结果嵌入称为[布局](structure-views.md#layouts)的文件中, 本例中是 `views/layouts/main.php`。 diff --git a/docs/guide-zh-CN/start-installation.md b/docs/guide-zh-CN/start-installation.md index 2bd8d5e..2c8af71 100644 --- a/docs/guide-zh-CN/start-installation.md +++ b/docs/guide-zh-CN/start-installation.md @@ -10,10 +10,10 @@ 在本章节和以后的章节,我们将会介绍如何去安装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应用程序。 +> Info: 这个基本的应用程序模板是适合于开发90%的Web应用程序。 它不同于高级的应用程序模板主要地在如何使它们的代码是有组织的。 如果你是刚接触Yii,我们强烈建议你坚持使用简单并有足够的功能的基础的应用程序模板。 @@ -21,7 +21,7 @@ Yii当然也提供了其它模板叫 通过 Composer 安装 ----------------------- -### Installing Composer +### 安装 Composer 如果还没有安装 Composer,你可以按 [getcomposer.org](https://getcomposer.org/download/) 中的方法安装。 在 Linux 和 Mac OS X 中可以运行如下命令: @@ -33,37 +33,55 @@ 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 : +在本指南中,所有 composer 命令都假定您已经安装了[全局](https://getcomposer.org/doc/00-intro.md#globally) 的 composer, +这样它可以作为 `composer` 命令。如果您在本地目录中使用 `composer.phar`, +则必须相应地调整示例命令。 + +如果您之前已安装 Composer,请确保使用最新版本。 +您可以通过运行 `composer self-update` 来更新Composer。 + +> Note: 在安装 Yii 期间,Composer 需要从 Github API 请求很多信息。 +> 请求的数量取决于您的应用程序所依赖的数量, +> 并可能大于 **Github API 速率限制**。如果达到此限制,Composer 可能会要求您提供 Github 登录凭据以获取 +> Github API 访问令牌。在快速连接上,您可能比 Composer 能够处理的时间早, +> 因此我们建议您在安装 Yii 之前配置访问令牌。 +> 有关如何执行此操作的说明,请参阅 +> [Composer documentation about Github API tokens](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)。 + +### 安装 Yii - composer global require "fxp/composer-asset-plugin:^1.4.1" - composer create-project --prefer-dist yiisoft/yii2-app-basic basic +安装 Composer 后,您可以通过在 Web 可访问的文件夹下运行以下命令来 +安装Yii应用程序模板: -第一条命令安装 [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 +``` -> Note: 在安装过程中 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))。 +这将在一个名为 `basic` 的目录中安装Yii应用程序模板的最新稳定版本。 +如果需要,您可以选择不同的目录名称。 + +> Info: 如果 `composer create-project` 命令失败,您也可以参考 +> [Composer 文档的疑难解答](https://getcomposer.org/doc/articles/troubleshooting.md) +> 部分中的常见错误。修复错误后, +> 您可以通过在 `basic` 目录内运行 `composer update` 来恢复中止安装。 > Tip: 如果你想安装 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)): +> 它添加了一个 [stability 选项](https://getcomposer.org/doc/04-schema.md#minimum-stability): > > ```bash > composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic > ``` > -> 注意,Yii 的开发版(dev 版)不应该用于生产环境中,它可能会破坏运行中的代码。 +> 请注意,Yii的开发版本不应该用于生产,因为它可能会破坏您的运行代码。 通过归档文件安装 -------------------------------- +-------------- 通过归档文件安装 Yii 包括三个步骤: @@ -79,7 +97,7 @@ Composer 安装后,切换到一个可通过 Web 访问的目录,执行如下 其他安装方式 --------------------------- +---------- 上文介绍了两种安装 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)。 + + +安装 Assets +----------- + +Yii依靠 [Bower](http://bower.io/) 和/或 [NPM](https://www.npmjs.org/) 软件包来安装 asset(CSS 和 JavaScript)库。 +它使用Composer来获取这些库,允许 PHP 和 CSS/JavaScript 包版本同时解析。 +这可以通过使用 [asset-packagist.org](https://asset-packagist.org) 或 [composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin/) 来实现。 +有关更多详细信息,请参阅 [Assets 文档](structure-assets.md)。 + +您可能希望通过本地 Bower/NPM 客户端管理您的 assets,使用 CDN 或完全避免 assets 的安装。 +为了防止通过 Composer 安装 assets,请将以下几行添加到您的 '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: 在通过 Composer 绕过 assets 安装的情况下,您负责 assets 的安装和解决版本冲突。 +> 准备来自不同扩展名的 assets 文件之间的可能不一致。 验证安装的结果 --------------------------- +------------ 当安装完成之后, 或配置你的Web服务器(看下面的文章)或使用[内置Web Server](https://secure.php.net/manual/en/features.commandline.webserver.php), @@ -153,14 +195,16 @@ URL `http://www.example.com/index.php` 访问而不是 `http://www.example.com/b 可能你还会想隐藏掉 URL 中的 `index.php`,具体细节在 [URL 解析和生成](runtime-url-handling.md)一章中有介绍, 你将学到如何配置 Apache 或 Nginx 服务器实现这些目标。 -> 信息:将 `basic/web` 设置为文档根目录(document root),可以防止终端用户访问 `basic/web` 相邻目录中 +> Info: 将 `basic/web` 设置为文档根目录(document root),可以防止终端用户访问 `basic/web` 相邻目录中 的私有应用代码和敏感数据文件。 禁止对其他目录的访问是一个不错的安全改进。 -> 信息:如果你的应用程序将来要运行在共享虚拟主机环境中, +> Info: 如果你的应用程序将来要运行在共享虚拟主机环境中, 没有修改其 Web 服务器配置的权限,你依然可以通过调整应用的结构来提升安全性。 详情请参考[共享主机环境](tutorial-shared-hosting.md) 一章。 +> Info: 如果您在反向代理后面运行Yii应用程序, +> 则可能需要在请求组件中配置 [Trusted proxies and headers](runtime-requests.md#trusted-proxies)。 ### 推荐使用的 Apache 配置 @@ -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] + # ...其它设置... ``` @@ -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; diff --git a/docs/guide-zh-CN/start-workflow.md b/docs/guide-zh-CN/start-workflow.md index 945bc09..4989879 100644 --- a/docs/guide-zh-CN/start-workflow.md +++ b/docs/guide-zh-CN/start-workflow.md @@ -6,7 +6,7 @@ 本章节将介绍应用的内建功能,如何组织代码, 以及一般情况下应用如何处理请求。 -> 信息:为简单起见,在整个“入门”板块都假定你已经把 +> Info: 为简单起见,在整个“入门”板块都假定你已经把 `basic/web` 设为 Web 服务器根目录并配置完毕, 你访问应用的地址会是 `http://hostname/index.php` 或类似的。 请按需调整 URL。 diff --git a/docs/guide-zh-CN/structure-application-components.md b/docs/guide-zh-CN/structure-application-components.md index c90f9d3..ce16e95 100644 --- a/docs/guide-zh-CN/structure-application-components.md +++ b/docs/guide-zh-CN/structure-application-components.md @@ -45,7 +45,7 @@ ] ``` -> 信息:请谨慎注册太多应用组件, +> Info: 请谨慎注册太多应用组件, 应用组件就像全局变量, 使用太多可能加大测试和维护的难度。 一般情况下可以在需要时再创建本地组件。 diff --git a/docs/guide-zh-CN/structure-applications.md b/docs/guide-zh-CN/structure-applications.md index 9310f44..45b1818 100644 --- a/docs/guide-zh-CN/structure-applications.md +++ b/docs/guide-zh-CN/structure-applications.md @@ -5,7 +5,7 @@ 每个Yii应用系统只能包含一个应用主体,应用主体在 [入口脚本](structure-entry-scripts.md) 中创建并能通过表达式 `\Yii::$app` 全局范围内访问。 -> 信息:当我们说"一个应用",它可能是一个应用主体对象,也可能是一个应用系统, +> Info: 当我们说"一个应用",它可能是一个应用主体对象,也可能是一个应用系统, 是根据上下文来决定[译:中文为避免歧义,Application翻译为应用主体]。 Yii有两种应用主体: [[yii\web\Application|网页应用主体]] and @@ -137,7 +137,7 @@ $config = require __DIR__ . '/../config/web.php'; ] ``` -> 信息:如果模块 ID 和应用组件 ID 同名,优先使用应用组件 ID, +> Info: 如果模块 ID 和应用组件 ID 同名,优先使用应用组件 ID, > 如果你想用模块 ID, > 可以使用如下无名称函数返回模块 ID。 > @@ -192,7 +192,7 @@ if (YII_ENV_DEV) { ] ``` -> 信息:当开启这个属性时,开发环境下的调试面板将不能工作。 +> Info: 当开启这个属性时,开发环境下的调试面板将不能工作。 #### [[yii\base\Application::components|components]] diff --git a/docs/guide-zh-CN/structure-assets.md b/docs/guide-zh-CN/structure-assets.md index e572930..d4763e1 100644 --- a/docs/guide-zh-CN/structure-assets.md +++ b/docs/guide-zh-CN/structure-assets.md @@ -114,7 +114,7 @@ class AppAsset extends AssetBundle 由于它们的资源和源代码都在不能Web访问的目录下, 在定义资源包类时必须指定[[yii\web\AssetBundle::sourcePath|sourcePath]]属性。 -> Note: [[yii\web\AssetBundle::sourcePath|source path]] 属性不要用`@webroot/assets`,该路径默认为 +> Note: [[yii\web\AssetBundle::sourcePath|source path]] 属性不要用 `@webroot/assets`,该路径默认为 [[yii\web\AssetManager|asset manager]]资源管理器将源资源发布后存储资源的路径, 该路径的所有内容会认为是临时文件, 可能会被删除。 @@ -231,7 +231,7 @@ use app\assets\AppAsset; AppAsset::register($this); // $this 代表视图对象 ``` -> 信息:The [[yii\web\AssetBundle::register()]] method returns an asset bundle object containing the information +> Info: The [[yii\web\AssetBundle::register()]] method returns an asset bundle object containing the information about the published assets, such as [[yii\web\AssetBundle::basePath|basePath]] or [[yii\web\AssetBundle::baseUrl|baseUrl]]. 如果在其他地方注册资源包,应提供视图对象,如在 [小部件](structure-widgets.md) 类中注册资源包, @@ -476,7 +476,7 @@ return [ 数组的值为目标资源文件扩展名和执行资源转换的命令, 命令中的标记 `{from}` 和`{to}`会分别被源资源文件路径和目标资源文件路径替代。 -> 信息:除了以上方式,也有其他的方式来处理扩展语法资源, +> Info: 除了以上方式,也有其他的方式来处理扩展语法资源, 例如,可使用编译工具如[grunt](http://gruntjs.com/) 来监控并自动转换扩展语法资源,此时, 应使用资源包中编译后的CSS/Javascript文件而不是原始文件。 @@ -488,7 +488,7 @@ return [ 通常的方式是在页面中合并并压缩多个CSS/JavaScript 文件为一个或很少的几个文件, 并使用压缩后的文件而不是原始文件。 -> 信息:合并和压缩资源通常在应用在产品上线模式, +> Info: 合并和压缩资源通常在应用在产品上线模式, 在开发模式下使用原始的CSS/JavaScript更方便调试。 接下来介绍一种合并和压缩资源文件 @@ -522,7 +522,7 @@ return [ 已合并的CSS和Javascipt文件会更大,因此会增加文件传输时间,在这个示例中, 我们使用第一种方式,也就是用一个组包含所有包。 -> 信息:将资源包分组并不是无价值的,通常要求分析现实中不同页面各种资源的数据量, +> Info: 将资源包分组并不是无价值的,通常要求分析现实中不同页面各种资源的数据量, 开始时为简便使用一个组。 在所有包中使用工具(例如 [Closure Compiler](https://developers.google.com/closure/compiler/), @@ -658,7 +658,7 @@ yii asset assets.php config/assets-prod.php 如最后一小节所描述的。 -> 信息:使用`asset` 命令并不是唯一一种自动合并和压缩过程的方法, +> Info: 使用`asset` 命令并不是唯一一种自动合并和压缩过程的方法, 可使用优秀的工具[grunt](http://gruntjs.com/)来完成这个过程。 @@ -707,5 +707,5 @@ As you can see, the asset bundles are divided into three groups: `allShared`, `a They each depends on an appropriate set of asset bundles. For example, `allBackEnd` depends on `app\assets\AdminAsset`. When running `asset` command with this configuration, it will combine asset bundles according to the above specification. -> 信息:You may leave the `depends` configuration empty for one of the target bundle. By doing so, that particular +> Info: You may leave the `depends` configuration empty for one of the target bundle. By doing so, that particular asset bundle will depend on all of the remaining asset bundles that other target bundles do not depend on. diff --git a/docs/guide-zh-CN/structure-controllers.md b/docs/guide-zh-CN/structure-controllers.md index 9899730..9372832 100644 --- a/docs/guide-zh-CN/structure-controllers.md +++ b/docs/guide-zh-CN/structure-controllers.md @@ -144,7 +144,7 @@ class SiteController extends Controller 为`@app/controllers/ArticleController.php`的文件中定义, 控制器`admin/post-comment`应在`@app/controllers/admin/PostCommentController.php`文件中。 -> 信息:最后一个示例 `admin/post-comment` 表示你可以将控制器放在 +> Info: 最后一个示例 `admin/post-comment` 表示你可以将控制器放在 [[yii\base\Application::controllerNamespace|controller namespace]]控制器命名空间下的子目录中, 在你不想用 [模块](structure-modules.md) 的情况下给控制器分类,这种方式很有用。 @@ -361,9 +361,9 @@ class PostController extends Controller * `http://hostname/index.php?r=post/view`: 会抛出[[yii\web\BadRequestHttpException]] 异常 因为请求没有提供参数给必须赋值参数`$id`; * `http://hostname/index.php?r=post/view&id[]=123`: 会抛出[[yii\web\BadRequestHttpException]] 异常 - 因为`$id` 参数收到数字值 `['123']`而不是字符串. + 因为 `$id` 参数收到数组值 `['123']` 而不是字符串. -如果想让动作参数接收数组值,需要指定$id为`array`,如下所示: +如果你想要一个动作参数来接受数组值,你应该使用 `array` 来提示它,如下所示: ```php public function actionView(array $id, $version = null) @@ -372,9 +372,9 @@ public function actionView(array $id, $version = null) } ``` -现在如果请求为 `http://hostname/index.php?r=post/view&id[]=123`, 参数 `$id` 会使用数组值`['123']`, +现在如果请求为 `http://hostname/index.php?r=post/view&id[]=123`, 参数 `$id` 会使用数组值 `['123']`, 如果请求为 `http://hostname/index.php?r=post/view&id=123`, -参数 `$id` 会获取相同数组值,因为无类型的`'123'`会自动转成数组。 +参数 `$id` 会获取相同数组值,因为无类型的 `'123'` 会自动转成数组。 上述例子主要描述网页应用的操作参数,对于控制台应用, 更多详情请参阅[控制台命令](tutorial-console.md)。 diff --git a/docs/guide-zh-CN/structure-extensions.md b/docs/guide-zh-CN/structure-extensions.md index ad88bc2..75d2dae 100644 --- a/docs/guide-zh-CN/structure-extensions.md +++ b/docs/guide-zh-CN/structure-extensions.md @@ -7,7 +7,7 @@ 帮助你简单地抓取页面生成的情况。 你可以使用扩展来加速你的开发过程。 -> 信息:本文中我们使用的术语 "扩展" 特指 Yii 软件包。而用术语 +> Info: 本文中我们使用的术语 "扩展" 特指 Yii 软件包。而用术语 "软件包" 和 "库" 指代非 Yii 专用的通常意义上的软件包。 @@ -47,7 +47,7 @@ 安装完成后,你应该能在 `BasePath/vendor` 目录下见到 `yiisoft/yii2-imagine` 目录。你也应该 见到另一个 `imagine/imagine` 目录,在其中安装了所依赖的包。 -> 信息: `yiisoft/yii2-imagine` 是 Yii 由开发团队维护一个核心扩展, +> Info: `yiisoft/yii2-imagine` 是 Yii 由开发团队维护一个核心扩展, 所有核心扩展均由 [Packagist](https://packagist.org/) 集中管理,命名为 `yiisoft/yii2-xyz`,其中的 `xyz`, 不同扩展有不同名称。 @@ -63,7 +63,7 @@ Image::thumbnail('@webroot/img/test-image.jpg', 120, 120) ->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]); ``` -> 信息: 扩展类由 [Yii class autoloader](concept-autoloading.md) 自动加载。 +> Info: 扩展类由 [Yii class autoloader](concept-autoloading.md) 自动加载。 ### 手动安装扩展 @@ -379,10 +379,10 @@ Yii 提供了测试支持,使你更容易写单元测试、验收测试和功 你可以参照 [Object class file](https://github.com/yiisoft/yii2/blob/master/framework/base/Object.php) 学习如何为你的代码做文档。 -> 信息:你的代码注释可以写成 Markdown 格式。`yiisoft/yii2-apidoc` 扩展为你提供了一个从你的 +> Info: 你的代码注释可以写成 Markdown 格式。`yiisoft/yii2-apidoc` 扩展为你提供了一个从你的 代码注释生成漂亮的 API 文档。 -> 信息:虽然不做要求,我们还是建议你的扩展遵循某个编码规范。 +> Info: 虽然不做要求,我们还是建议你的扩展遵循某个编码规范。 你可以参照 [core framework code style](https://github.com/yiisoft/yii2/wiki/Core-framework-code-style)。 diff --git a/docs/guide-zh-CN/structure-filters.md b/docs/guide-zh-CN/structure-filters.md index 1531838..67db632 100644 --- a/docs/guide-zh-CN/structure-filters.md +++ b/docs/guide-zh-CN/structure-filters.md @@ -224,7 +224,7 @@ use yii\web\Response; ]; ``` -> 信息:如果请求中没有检测到内容格式和语言, +> Info: 如果请求中没有检测到内容格式和语言, 使用 [[formats]] 和 [[languages]] 第一个配置项。 diff --git a/docs/guide-zh-CN/structure-models.md b/docs/guide-zh-CN/structure-models.md index 21ad1e6..f94520c 100644 --- a/docs/guide-zh-CN/structure-models.md +++ b/docs/guide-zh-CN/structure-models.md @@ -17,7 +17,7 @@ `Model` 类也是更多高级模型如[Active Record 活动记录](db-active-record.md)的基类, 更多关于这些高级模型的详情请参考相关手册。 -> 信息:模型并不强制一定要继承[[yii\base\Model]],但是由于很多组件支持[[yii\base\Model]], +> Info: 模型并不强制一定要继承[[yii\base\Model]],但是由于很多组件支持[[yii\base\Model]], 最好使用它做为模型基类。 @@ -147,7 +147,7 @@ public function attributeLabels() 甚至可以根据条件定义标签,例如通过使用模型的 [scenario场景](#scenarios), 可对相同的属性返回不同的标签。 -> 信息:属性标签是 [视图](structure-views.md)一部分, +> Info: 属性标签是 [视图](structure-views.md)一部分,  但是在模型中声明标签通常非常方便,并可形成非常简洁可重用代码。 @@ -195,7 +195,7 @@ class User extends ActiveRecord } ``` -> 信息:在上述和下述的例子中,模型类都是继承[[yii\db\ActiveRecord]], +> Info: 在上述和下述的例子中,模型类都是继承[[yii\db\ActiveRecord]], 因为多场景的使用通常发生在[Active Record](db-active-record.md) 类中. `scenarios()` 方法返回一个数组,数组的键为场景名,值为对应的 *active attributes活动属性*。 @@ -345,7 +345,7 @@ public function scenarios() } ``` -> 信息:块赋值只应用在安全属性上, +> Info: 块赋值只应用在安全属性上, 因为你想控制哪些属性会被终端用户输入数据所修改, 例如,如果 `User` 模型有一个`permission`属性对应用户的权限, 你可能只想让这个属性在后台界面被管理员修改。 diff --git a/docs/guide-zh-CN/structure-modules.md b/docs/guide-zh-CN/structure-modules.md index 7532d8f..c4c7074 100644 --- a/docs/guide-zh-CN/structure-modules.md +++ b/docs/guide-zh-CN/structure-modules.md @@ -191,7 +191,7 @@ $module = MyModuleClass::getInstance(); 如果模块没有被请求,该方法会返回空,注意不需要手动创建一个模块类, 因为手动创建的和Yii处理请求时自动创建的不同。 -> 信息:当开发模块时,你不能假定模块使用固定的ID, +> Info: 当开发模块时,你不能假定模块使用固定的ID, 因为在应用或其他没模块中,模块可能会对应到任意的ID, 为了获取模块ID,应使用上述代码获取模块实例, 然后通过`$module->id`获取模块ID。 @@ -265,7 +265,7 @@ class Module extends \yii\base\Module 例如`forum/admin/dashboard/index` 代表 在模块`forum`中子模块`admin`中`dashboard`控制器的`index`操作。 -> 信息:[[yii\base\Module::getModule()|getModule()]] 方法只返回子模块的直属的 +> Info: [[yii\base\Module::getModule()|getModule()]] 方法只返回子模块的直属的 父模块。 [[yii\base\Application::loadedModules]] 保存了已加所有载模块的属性, 包括两者的子模块和 嵌套模块,并用他们的类名进行索引。 diff --git a/docs/guide-zh-CN/structure-widgets.md b/docs/guide-zh-CN/structure-widgets.md index 52594b0..cea7a98 100644 --- a/docs/guide-zh-CN/structure-widgets.md +++ b/docs/guide-zh-CN/structure-widgets.md @@ -155,7 +155,7 @@ class HelloWidget extends Widget 如上所示,PHP输出缓冲在`init()`启动,所有在`init()` 和 `run()`方法之间的输出内容都会被获取,并在`run()`处理和返回。 -> 信息:当你调用 [[yii\base\Widget::begin()]] 时会创建一个新的小部件 +> Info: 当你调用 [[yii\base\Widget::begin()]] 时会创建一个新的小部件 实例并在构造结束时调用`init()`方法, 在`end()`时会调用`run()`方法并输出返回结果。 diff --git a/docs/guide-zh-CN/test-overview.md b/docs/guide-zh-CN/test-overview.md index dd84caa..0f07f6d 100644 --- a/docs/guide-zh-CN/test-overview.md +++ b/docs/guide-zh-CN/test-overview.md @@ -7,12 +7,12 @@ 一些测试数据来确保页面能够如预期那样和我们进行交互。 测试过程可能是自动的,所以每次我们需要验证的时候,我们只需要调用它就可以测试代码 -了。 验证代码执行结果是否符合我们的计划叫做测试,测试过程的创建以及进一步执行叫做 -自动化测试,这是这些测试章节的主要主题。 +了。 验证代码执行结果是否符合我们的计划叫做测试, +测试过程的创建以及进一步执行叫做*自动化测试*, +这是这些测试章节的主要主题。 -带着测试进行开发 ------------------- +## 带着测试进行开发 测试驱动开发(TDD)和行为驱动开发(BDD)在开始编写实际代码之前, 首先通过描述一段代码的行为或将其作为一组场景或测试的全部特征, @@ -30,7 +30,7 @@ 走完上面的过程之后,为其他功能或者扩展重复上面测试过程。如果功能发生变化,测试也需 要跟着变化。 -> Note: 如果你觉得你做一些很小很简单的迭代是在浪费时间,请尝试覆盖更多的测试 +> Tip: 如果你觉得你做一些很小很简单的迭代是在浪费时间,请尝试覆盖更多的测试 > 场景,这样你就可以在执行测试之前做更多的尝试。如果你的调试过多,试着做相反的工作。 在做一些具体的实现之前创建测试的原因是,这允许我们后期专注于我们想要的实现,并且 @@ -44,11 +44,7 @@ 在很长一段时间内,这通常会给你提供一个有效的时间节省。 -> **技巧**: 如果你想了解更多关于收集软件需求和建模的原则,最好去学习 -[Domain Driven Development (DDD)](https://en.wikipedia.org/wiki/Domain-driven_design)。 - -什么时候测试,怎么测试? ------------------- +## 什么时候测试,怎么测试? 在测试的时候,对于一些相对复杂的项目上面的内容是非常有意义的,但对于一些比较 简单的项目就做的有些极端了。适用场景如下: @@ -70,7 +66,7 @@ 假如你有很多的时间,在这种情况下进行自动测试也很好。 -深度阅读 -------------- +## 深度阅读 - Test Driven Development: By Example / Kent Beck. ISBN: 0321146530. + diff --git a/docs/guide-zh-CN/tutorial-console.md b/docs/guide-zh-CN/tutorial-console.md index 0fdea15..00ace8a 100644 --- a/docs/guide-zh-CN/tutorial-console.md +++ b/docs/guide-zh-CN/tutorial-console.md @@ -50,12 +50,12 @@ yii [--option1=value1 --option2=value2 ... argument1 argument2 ...] yii migrate/up 5 --migrationTable=migrations ``` -> **注意**: 当在控制台使用 `*` 时, 不要忘记像 `"*"` 一样用引号来引起来, +> Note: 当在控制台使用 `*` 时, 不要忘记像 `"*"` 一样用引号来引起来, > 为了防止在 shell 中执行命令时被当成当前目录下的所有文件名。 入口脚本 ----------------- +------- 控制台应用程序的入口脚本相当于用于 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); > ``` +控制台命令完成 +------------ + +自动完成命令参数在使用 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 +``` + 创建你自己的控制台命令 ----------------------- +------------------ ### 控制台的控制器和行为 @@ -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]]. diff --git a/docs/guide-zh-CN/tutorial-mailing.md b/docs/guide-zh-CN/tutorial-mailing.md index 84d3437..6d3a6e0 100644 --- a/docs/guide-zh-CN/tutorial-mailing.md +++ b/docs/guide-zh-CN/tutorial-mailing.md @@ -60,7 +60,7 @@ $message->setTo(Yii::$app->params['adminEmail']) ->send(); ``` -> Note: 每个 “mailer” 的扩展也有两个主要类别:“Mailer” +> Note: 每个 “mailer” 的扩展也有两个主要类别:“Mailer” 和 “Message”。 “Mailer” 总是知道类名和具体的 “Message”。 不要试图直接实例 “Message” 对象 - 而是始终使用 `compose()` 方法。 diff --git a/docs/guide-zh-CN/tutorial-yii-as-micro-framework.md b/docs/guide-zh-CN/tutorial-yii-as-micro-framework.md index 38438c3..7d0dd8e 100644 --- a/docs/guide-zh-CN/tutorial-yii-as-micro-framework.md +++ b/docs/guide-zh-CN/tutorial-yii-as-micro-framework.md @@ -70,7 +70,7 @@ return [ ]; ``` -> 信息:尽管配置可以保存在 `index.php` 文件中,建议单独使用它。 +> Info: 尽管配置可以保存在 `index.php` 文件中,建议单独使用它。 > 这样它也可以用于控制台应用程序,如下所示。 您的项目现在已经准备进行编码了。尽管由您决定项目目录结构,只要您遵守命名空间即可。 @@ -119,7 +119,7 @@ micro-app/ 在浏览器中打开应用程序URL现在应该打印出“Hello World!”,它已经在 `SiteController::actionIndex()` 中返回。 -> 信息:在我们的示例中,我们已将默认应用程序名称空间 `app` 更改为 `micro`, +> Info: 在我们的示例中,我们已将默认应用程序名称空间 `app` 更改为 `micro`, > 以表明您不受此名称的限制(如果您是这样认为), > 然后调整 [[yii\base\Application::$controllerNamespace|controllers namespace]] 并设置正确的别名。 @@ -140,7 +140,7 @@ micro-app/ ], ``` -> 信息:为了简单,我们在这里使用了一个 sqlite 数据库 请参阅[数据库指南](db-dao.md) 以获取更多选项。 +> Info: 为了简单,我们在这里使用了一个 sqlite 数据库 请参阅[数据库指南](db-dao.md) 以获取更多选项。 接下来我们创建一个[数据库迁移](db-migrations.md)来创建一个帖子表。 确保你有一个单独的配置文件,如上所述,我们需要它来运行下面的控制台命令。 @@ -168,7 +168,7 @@ class Post extends ActiveRecord } ``` -> 信息:这里创建的模型是一个 ActiveRecord 类,它代表 `post` 表中的数据。 +> Info: 这里创建的模型是一个 ActiveRecord 类,它代表 `post` 表中的数据。 > 有关更多信息,请参阅[活动记录指南](db-active-record.md)。 我们要通过 API 发布帖子,请在 `controllers` 中添加 `PostController`: From 88fc42329f37d224768cecabc3cedf95dfd15ad7 Mon Sep 17 00:00:00 2001 From: pvlg Date: Fri, 13 Apr 2018 00:37:26 +0300 Subject: [PATCH 05/12] Update security-authorization.md (#16082) [skip ci] --- docs/guide/security-authorization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index 620e47c..dcacc40 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -599,7 +599,7 @@ If the creation of role parameters is a simple operation, you may just specify a 'allow' => true, 'actions' => ['update'], 'roles' => ['updatePost'], - 'roleParams' => ['postId' => Yii::$app->request->get('id')]; + 'roleParams' => ['postId' => Yii::$app->request->get('id')], ], ``` From c3414cad126f64a4280c6e3779ce139af2077777 Mon Sep 17 00:00:00 2001 From: Nobuo Kihara Date: Fri, 13 Apr 2018 06:38:59 +0900 Subject: [PATCH 06/12] docs/guide-ja/start-prerequisites.md updated [ci skip] (#16079) --- docs/guide-ja/start-prerequisites.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/guide-ja/start-prerequisites.md b/docs/guide-ja/start-prerequisites.md index 8c26c7e..c31cd7c 100644 --- a/docs/guide-ja/start-prerequisites.md +++ b/docs/guide-ja/start-prerequisites.md @@ -1,10 +1,12 @@ # 何を知っている必要があるか -Yii の学習曲線は他の PHP フレームワークほど急峻ではありませんが、それでもいくつかは事前に必要とされる知識があります。 +Yii の学習曲線は他の PHP フレームワークほど急峻ではありませんが、それでも Yii を使い始める前に学習すべき事がいくつかはあります。 ## PHP Yii は PHP フレームワークですから、必ず [言語リファレンスを読んで理解する](http://php.net/manual/ja/langref.php) ようにして下さい。 +Yii を使って開発するときはオブジェクト指向でコードを書くことになりますから、必ず、 +[クラスとオブジェクト](https://secure.php.net/manual/ja/language.oop5.basic.php) および [名前空間](https://secure.php.net/manual/ja/language.namespaces.php) には慣れ親しんでおいて下さい。 ## オブジェクト指向プログラミング @@ -15,6 +17,7 @@ Yii は PHP フレームワークですから、必ず [言語リファレンス ## コマンドラインと Composer -Yii は業界標準の PHP パッケージ管理ソフトである [Composer](https://getcomposer.org/) を広範囲に使用していますので、必ずそのガイドを読んで理解して下さい。 +Yii は業界標準の PHP パッケージ管理ソフトである [Composer](https://getcomposer.org/) を広範囲に使用していますので、 +必ずその [ガイド](https://getcomposer.org/doc/01-basic-usage.md) を読んで理解して下さい。 あなたがコマンドラインの使用に慣れていないのであれば、今こそ使い始めてみるべき時です。 いったん基礎を学習すれば、二度とコマンドラインなしで仕事をしようとは思わなくなりますよ。 From abeb3b1a371a3b0babe3fae2d7d6a36765b03bc0 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 13 Apr 2018 13:53:06 +0200 Subject: [PATCH 07/12] Fixes #16073: Fixed regression in Oracle `IN` condition builder for more than 1000 items --- framework/CHANGELOG.md | 2 ++ framework/db/oci/conditions/InConditionBuilder.php | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index fa09056..972049b 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -9,6 +9,8 @@ Yii Framework 2 Change Log - Bug #14660: Fixed `yii\caching\DbCache` concurrency issue when set values with the same key (rugabarbo) - Bug #15988: Fixed bash completion (alekciy) - Bug #15117: Fixed `yii\db\Schema::getTableMetadata` cache refreshing (boboldehampsink) +- Bug #16073: Fixed regression in Oracle `IN` condition builder for more than 1000 items (cebe) + 2.0.15.1 March 21, 2018 ----------------------- diff --git a/framework/db/oci/conditions/InConditionBuilder.php b/framework/db/oci/conditions/InConditionBuilder.php index 131bf5b..2a94775 100644 --- a/framework/db/oci/conditions/InConditionBuilder.php +++ b/framework/db/oci/conditions/InConditionBuilder.php @@ -65,7 +65,8 @@ class InConditionBuilder extends \yii\db\conditions\InConditionBuilder for ($i = 0; $i < $count; $i += $maxParameters) { $slices[] = $this->queryBuilder->createConditionFromArray([$operator, $column, array_slice($values, $i, $maxParameters)]); } + array_unshift($slices, ($operator === 'IN') ? 'OR' : 'AND'); - return $this->queryBuilder->buildCondition([($operator === 'IN') ? 'OR' : 'AND', $slices], $params); + return $this->queryBuilder->buildCondition($slices, $params); } } From 7b08f37a6f9038f7624065334f9cd272b3d0b3cc Mon Sep 17 00:00:00 2001 From: Nobuo Kihara Date: Mon, 16 Apr 2018 17:27:14 +0900 Subject: [PATCH 08/12] link fix in Doc/guide/README.md [ci skip] (#16098) * link fix in Doc/guide/README.md [ci skip] * doc/guide/start-databases.md link fixed [ci skip] * docs/guide/start-gii.md link fixed [ci skip] * docs/guide/start-looking-ahead.md link fixed [ci skip] --- docs/guide/README.md | 20 ++++++++++---------- docs/guide/intro-upgrade-from-v1.md | 2 +- docs/guide/start-databases.md | 4 ++-- docs/guide/start-gii.md | 6 +++--- docs/guide/start-looking-ahead.md | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/guide/README.md b/docs/guide/README.md index 950bc20..04972e6 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -75,11 +75,11 @@ Key Concepts Working with Databases ---------------------- -* [Data Access Objects](db-dao.md): Connecting to a database, basic queries, transactions, and schema manipulation +* [Database Access Objects](db-dao.md): Connecting to a database, basic queries, transactions, and schema manipulation * [Query Builder](db-query-builder.md): Querying the database using a simple abstraction layer * [Active Record](db-active-record.md): The Active Record ORM, retrieving and manipulating records, and defining relations * [Migrations](db-migrations.md): Apply version control to your databases in a team development environment -* [Sphinx](https://yiiframework.com/extension/yiisoft/yii2-sphinx/doc/guide) +* [Sphinx](https://www.yiiframework.com/extension/yiisoft/yii2-sphinx/doc/guide) * [Redis](https://www.yiiframework.com/extension/yiisoft/yii2-redis/doc/guide) * [MongoDB](https://www.yiiframework.com/extension/yiisoft/yii2-mongodb/doc/guide) * [ElasticSearch](https://www.yiiframework.com/extension/yiisoft/yii2-elasticsearch/doc/guide) @@ -183,14 +183,14 @@ Special Topics Widgets ------- -* [GridView](http://www.yiiframework.com/doc-2.0/yii-grid-gridview.html) -* [ListView](http://www.yiiframework.com/doc-2.0/yii-widgets-listview.html) -* [DetailView](http://www.yiiframework.com/doc-2.0/yii-widgets-detailview.html) -* [ActiveForm](http://www.yiiframework.com/doc-2.0/guide-input-forms.html#activerecord-based-forms-activeform) -* [Pjax](http://www.yiiframework.com/doc-2.0/yii-widgets-pjax.html) -* [Menu](http://www.yiiframework.com/doc-2.0/yii-widgets-menu.html) -* [LinkPager](http://www.yiiframework.com/doc-2.0/yii-widgets-linkpager.html) -* [LinkSorter](http://www.yiiframework.com/doc-2.0/yii-widgets-linksorter.html) +* [[yii\grid\GridView|GridView]] +* [[yii\widgets\ListView|ListView]] +* [[yii\widgets\DetailView|DetailView]] +* [[yii\widgets\ActiveForm|ActiveForm]] +* [[yii\widgets\Pjax|Pjax]] +* [[yii\widgets\Menu|Menu]] +* [[yii\widgets\LinkPager|LinkPager]] +* [[yii\widgets\LinkSorter|LinkSorter]] * [Bootstrap Widgets](https://www.yiiframework.com/extension/yiisoft/yii2-bootstrap/doc/guide) * [jQuery UI Widgets](https://www.yiiframework.com/extension/yiisoft/yii2-jui/doc/guide) diff --git a/docs/guide/intro-upgrade-from-v1.md b/docs/guide/intro-upgrade-from-v1.md index 2c521ff..2565460 100644 --- a/docs/guide/intro-upgrade-from-v1.md +++ b/docs/guide/intro-upgrade-from-v1.md @@ -505,7 +505,7 @@ The `CWebUser` class in 1.1 is now replaced by [[yii\web\User]], and there is no `CUserIdentity` class. Instead, you should implement the [[yii\web\IdentityInterface]] which is much more straightforward to use. The advanced project template provides such an example. -Please refer to the [Authentication](security-authentication.md), [Authorization](security-authorization.md), and [Advanced Project Template](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md) sections for more details. +Please refer to the [Authentication](security-authentication.md), [Authorization](security-authorization.md), and [Advanced Project Template](https://www.yiiframework.com/extension/yiisoft/yii2-app-advanced/doc/guide) sections for more details. URL Management diff --git a/docs/guide/start-databases.md b/docs/guide/start-databases.md index d2bb26c..6dec3eb 100644 --- a/docs/guide/start-databases.md +++ b/docs/guide/start-databases.md @@ -129,7 +129,7 @@ $country->save(); ``` > Info: Active Record is a powerful way to access and manipulate database data in an object-oriented fashion. -You may find more detailed information in the [Active Record](db-active-record.md) section. Alternatively, you may also interact with a database using a lower-level data accessing method called [Data Access Objects](db-dao.md). +You may find more detailed information in the [Active Record](db-active-record.md) section. Alternatively, you may also interact with a database using a lower-level data accessing method called [Database Access Objects](db-dao.md). Creating an Action @@ -257,7 +257,7 @@ Summary In this section, you learned how to work with a database. You also learned how to fetch and display data in pages with the help of [[yii\data\Pagination]] and [[yii\widgets\LinkPager]]. -In the next section, you will learn how to use the powerful code generation tool, called [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md), +In the next section, you will learn how to use the powerful code generation tool, called [Gii](https://www.yiiframework.com/extension/yiisoft/yii2-gii/doc/guide), to help you rapidly implement some commonly required features, such as the Create-Read-Update-Delete (CRUD) operations for working with the data in a database table. As a matter of fact, the code you have just written can all be automatically generated in Yii using the Gii tool. diff --git a/docs/guide/start-gii.md b/docs/guide/start-gii.md index 83e8b2c..e4adf45 100644 --- a/docs/guide/start-gii.md +++ b/docs/guide/start-gii.md @@ -1,7 +1,7 @@ Generating Code with Gii ======================== -This section will describe how to use [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) to automatically generate code +This section will describe how to use [Gii](https://www.yiiframework.com/extension/yiisoft/yii2-gii/doc/guide) to automatically generate code that implements some common Web site features. Using Gii to auto-generate code is simply a matter of entering the right information per the instructions shown on the Gii Web pages. Through this tutorial, you will learn how to: @@ -15,7 +15,7 @@ Through this tutorial, you will learn how to: Starting Gii ------------ -[Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) is provided in Yii as a [module](structure-modules.md). You can enable Gii +[Gii](https://www.yiiframework.com/extension/yiisoft/yii2-gii/doc/guide) is provided in Yii as a [module](structure-modules.md). You can enable Gii by configuring it in the [[yii\base\Application::modules|modules]] property of the application. Depending upon how you created your application, you may find the following code is already provided in the `config/web.php` configuration file: ```php @@ -129,7 +129,7 @@ or to customize them: > Info: Gii is designed to be a highly customizable and extensible code generation tool. Using it wisely can greatly accelerate your application development speed. For more details, please refer to - the [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) section. + the [Gii](https://www.yiiframework.com/extension/yiisoft/yii2-gii/doc/guide) section. Summary diff --git a/docs/guide/start-looking-ahead.md b/docs/guide/start-looking-ahead.md index 736211c..b496480 100644 --- a/docs/guide/start-looking-ahead.md +++ b/docs/guide/start-looking-ahead.md @@ -3,7 +3,7 @@ Looking Ahead If you've read through the entire "Getting Started" chapter, you have now created a complete Yii application. In the process, you have learned how to implement some commonly needed features, such as getting data from users via an HTML form, fetching data from a database, and -displaying data in a paginated fashion. You have also learned how to use [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) to generate +displaying data in a paginated fashion. You have also learned how to use [Gii](https://www.yiiframework.com/extension/yiisoft/yii2-gii/doc/guide) to generate code automatically. Using Gii for code generation turns the bulk of your Web development process into a task as simple as just filling out some forms. This section will summarize the Yii resources available to help you be more productive when using the framework. From 14984328e5794b9b5b89789fa71d912ce6038bbd Mon Sep 17 00:00:00 2001 From: Vladimir Reznichenko Date: Mon, 16 Apr 2018 12:22:54 +0200 Subject: [PATCH 09/12] SCA with Php Inspections (EA Ultimate) (#16105) --- framework/base/Controller.php | 2 +- framework/helpers/BaseInflector.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 618aa56..9120c17 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -226,7 +226,7 @@ class Controller extends Component implements ViewContextInterface if (isset($actionMap[$id])) { return Yii::createObject($actionMap[$id], [$id, $this]); } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) { - $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id)))); + $methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id))); if (method_exists($this, $methodName)) { $method = new \ReflectionMethod($this, $methodName); if ($method->isPublic() && $method->getName() === $methodName) { diff --git a/framework/helpers/BaseInflector.php b/framework/helpers/BaseInflector.php index d3ddfaa..416f002 100644 --- a/framework/helpers/BaseInflector.php +++ b/framework/helpers/BaseInflector.php @@ -407,7 +407,7 @@ class BaseInflector */ public static function id2camel($id, $separator = '-') { - return str_replace(' ', '', ucwords(implode(' ', explode($separator, $id)))); + return str_replace(' ', '', ucwords(str_replace($separator, ' ', $id))); } /** From 033f2b4a13d31a5f202810eef9fad6e2c2f5e7bd Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Mon, 16 Apr 2018 17:48:44 +0300 Subject: [PATCH 10/12] Fixes #16108: Use less confusing syntax [skip ci] --- docs/guide/input-validation.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/input-validation.md b/docs/guide/input-validation.md index fc69434..88fec0f 100644 --- a/docs/guide/input-validation.md +++ b/docs/guide/input-validation.md @@ -294,7 +294,7 @@ which supports declaring both attributes and rules on the fly. Its usage is like ```php public function actionSearch($name, $email) { - $model = DynamicModel::validateData(compact('name', 'email'), [ + $model = DynamicModel::validateData(['name' => $name, 'email' => $email]), [ [['name', 'email'], 'string', 'max' => 128], ['email', 'email'], ]); @@ -316,7 +316,7 @@ Alternatively, you may use the following more "classic" syntax to perform ad hoc ```php public function actionSearch($name, $email) { - $model = new DynamicModel(compact('name', 'email')); + $model = new DynamicModel(['name' => $name, 'email' => $email]); $model->addRule(['name', 'email'], 'string', ['max' => 128]) ->addRule('email', 'email') ->validate(); From 3485d7e9e0ae2cb73135101d388f57305a0bd996 Mon Sep 17 00:00:00 2001 From: Nobuo Kihara Date: Tue, 17 Apr 2018 19:38:14 +0900 Subject: [PATCH 11/12] doc/guide/structure-application-components.md small fix [ci skip] (#16111) --- docs/guide/structure-application-components.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/structure-application-components.md b/docs/guide/structure-application-components.md index 3f18c2b..104c8fe 100644 --- a/docs/guide/structure-application-components.md +++ b/docs/guide/structure-application-components.md @@ -97,11 +97,11 @@ like you do with normal application components. When you are configuring a core if you do not specify its class, the default one will be used. * [[yii\web\AssetManager|assetManager]]: manages asset bundles and asset publishing. - Please refer to the [Managing Assets](structure-assets.md) section for more details. + Please refer to the [Assets](structure-assets.md) section for more details. * [[yii\db\Connection|db]]: represents a database connection through which you can perform DB queries. Note that when you configure this component, you must specify the component class as well as other required component properties, such as [[yii\db\Connection::dsn]]. - Please refer to the [Data Access Objects](db-dao.md) section for more details. + Please refer to the [Database Access Objects](db-dao.md) section for more details. * [[yii\base\Application::errorHandler|errorHandler]]: handles PHP errors and exceptions. Please refer to the [Handling Errors](runtime-handling-errors.md) section for more details. * [[yii\i18n\Formatter|formatter]]: formats data when they are displayed to end users. For example, a number From cf095445e032125cd692bfce84869178662df78a Mon Sep 17 00:00:00 2001 From: Bodilych Date: Tue, 17 Apr 2018 16:11:50 +0300 Subject: [PATCH 12/12] Update tutorial-yii-as-micro-framework.md (#16113) --- docs/guide-ru/tutorial-yii-as-micro-framework.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide-ru/tutorial-yii-as-micro-framework.md b/docs/guide-ru/tutorial-yii-as-micro-framework.md index 2aa3a82..575e344 100644 --- a/docs/guide-ru/tutorial-yii-as-micro-framework.md +++ b/docs/guide-ru/tutorial-yii-as-micro-framework.md @@ -31,7 +31,7 @@ cd micro-app } ``` -Сохраните файл и запустите команду `comper install`. Это установит framework со всеми его зависимостями. +Сохраните файл и запустите команду `composer install`. Это установит framework со всеми его зависимостями. ## Создание структуры проекта