mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-03 13:58:55 +08:00
Merge branch 'master' of git://github.com/yiisoft/yii2 into guide-pl
This commit is contained in:
@ -8,10 +8,6 @@
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
define('YII_DEBUG', true);
|
||||
|
||||
$composerAutoload = [
|
||||
|
||||
@ -112,7 +112,7 @@ Por esta razón, los IDs de controladores son a menudo sustantivos de los tipos
|
||||
Por ejemplo, podrías utilizar `article` como el ID de un controlador que maneja datos de artículos.
|
||||
|
||||
Por defecto, los IDs de controladores deberían contener sólo estos caracteres: letras del Inglés en minúscula, dígitos,
|
||||
guiones bajos y medios, y barras. Por ejemplo, `article`, `post-comment`, `admin/post2-comment` son todos
|
||||
guiones bajos y medios, y barras. Por ejemplo, `article`, `post-comment`, `admin/post-comment` son todos
|
||||
IDs de controladores válidos, mientras que `article?`, `PostComment`, `admin\post` no lo son.
|
||||
|
||||
Los guiones en un ID de controlador son utilizados para separar palabras, mientras que las barras diagonales lo son para
|
||||
@ -134,14 +134,14 @@ toma el valor por defecto: `app\controllers`:
|
||||
|
||||
* `article` deriva en `app\controllers\ArticleController`;
|
||||
* `post-comment` deriva en `app\controllers\PostCommentController`;
|
||||
* `admin/post2-comment` deriva en `app\controllers\admin\Post2CommentController`.
|
||||
* `admin/post-comment` deriva en `app\controllers\admin\PostCommentController`.
|
||||
|
||||
Las clases de controladores deben ser [autocargables](concept-autoloading.md). Por esta razón, en los ejemplos anteriores,
|
||||
la clase del controlador `article` debe ser guardada en un archivo cuyo alias [alias](concept-aliases.md)
|
||||
es `@app/controllers/ArticleController.php`; mientras que el controlador `admin/post2-comment` debería estar
|
||||
en `@app/controllers/admin/Post2CommentController.php`.
|
||||
es `@app/controllers/ArticleController.php`; mientras que el controlador `admin/post-comment` debería estar
|
||||
en `@app/controllers/admin/PostCommentController.php`.
|
||||
|
||||
> Información: En el último ejemplo, `admin/post2-comment`, demuestra cómo puedes poner un controlador bajo un sub-directorio
|
||||
> Información: En el último ejemplo, `admin/post-comment`, demuestra cómo puedes poner un controlador bajo un sub-directorio
|
||||
del [[yii\base\Application::controllerNamespace|controller namespace]]. Esto es útil cuando quieres organizar
|
||||
tus controladores en varias categorías pero sin utilizar [módulos](structure-modules.md).
|
||||
|
||||
|
||||
@ -63,10 +63,6 @@ De la misma manera, el siguiente código es el script de entrada para la [aplica
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// el fcgi no tiene STDIN y STDOUT definidos por defecto
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// registrar el cargador automático de Composer
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -64,10 +64,6 @@ De même, le code qui suit est le code du script de démarrage d'une application
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// register Composer autoloader
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -136,9 +136,9 @@ class SiteController extends Controller
|
||||
|
||||
コントローラクラスは [オートロード可能](concept-autoloading.md) でなければなりません。
|
||||
この理由により、上記の例の `aritcle` コントローラクラスは [エイリアス](concept-aliases.md) が `@app/controllers/ArticleController.php` であるファイルに保存されるべきものとなります。
|
||||
一方、`admin/post2-comment` コントローラは `@app/controllers/admin/Post2CommentController.php` というエイリアスのファイルに保存されるべきものとなります。
|
||||
一方、`admin/post-comment` コントローラは `@app/controllers/admin/PostCommentController.php` というエイリアスのファイルに保存されるべきものとなります。
|
||||
|
||||
> Info|情報: 最後の例である `admin/post2-comment` は、どうすれば [[yii\base\Application::controllerNamespace|コントローラ名前空間]] のサブディレクトリにコントローラを置くことが出来るかを示しています。
|
||||
> Info|情報: 最後の例である `admin/post-comment` は、どうすれば [[yii\base\Application::controllerNamespace|コントローラ名前空間]] のサブディレクトリにコントローラを置くことが出来るかを示しています。
|
||||
この方法は、コントローラをいくつかのカテゴリに分けて編成したい、けれども [モジュール](structure-modules.md) は使いたくない、という場合に役立ちます。
|
||||
|
||||
|
||||
|
||||
@ -62,10 +62,6 @@ $config = require(__DIR__ . '/../config/web.php');
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// デフォルトでは fcgi が STDIN と STDOUT を定義していないので
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// Composer のオートローダを登録
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -67,10 +67,6 @@ yii migrate/up 5 --migrationTable=migrations
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi では、デフォルトでは、STDIN と STDOUT が定義されていない
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
|
||||
|
||||
|
||||
@ -154,9 +154,9 @@ tenha por padrão o valor `app\controllers`:
|
||||
As classes dos controllers devem ser [autoloadable](concept-autoloading.md).
|
||||
Por esta razão, nos exemplos anteriores, o controller `article` deve ser salvo
|
||||
no arquivo cuja [alias](concept-aliases.md) é `@app/controllers/ArticleController.php`;
|
||||
enquanto o controller `admin/post2-comment` deve ser salvo no `@app/controllers/admin/Post2CommentController.php`.
|
||||
enquanto o controller `admin/post-comment` deve ser salvo no `@app/controllers/admin/PostCommentController.php`.
|
||||
|
||||
> Informação: No último exemplo `admin/post2-comment`, mostra como você pode colocar
|
||||
> Informação: No último exemplo `admin/post-comment`, mostra como você pode colocar
|
||||
um controller em um subdiretório do [[yii\base\Application::controllerNamespace|namespace controller]]. Isto é útil quando você quiser organizar seus controllers em diversas
|
||||
categorias e não quiser usar [módulos](structure-modules.md).
|
||||
|
||||
|
||||
@ -69,10 +69,6 @@ do console:
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// o fcgi não tem STDIN e STDOUT definidos por padrão
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// registra o autoloader do Composer
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -139,9 +139,9 @@ ID контроллеров также могут содержать префи
|
||||
|
||||
Классы контроллеров должны быть [автозагружаемыми](concept-autoloading.md). Именно по этой причине, в вышеприведенном примере,
|
||||
контроллер `article` должен быть сохранен в файл, [псевдоним](concept-aliases.md) которого `@app/controllers/ArticleController.php`;
|
||||
в то время как контроллер `admin/post2-comment` должен находиться в файле `@app/controllers/admin/Post2CommentController.php`.
|
||||
в то время как контроллер `admin/post-comment` должен находиться в файле `@app/controllers/admin/PostCommentController.php`.
|
||||
|
||||
> Информация: Последний пример `admin/post2-comment` показывает каким образом вы можете расположить контроллер в подпапке
|
||||
> Информация: Последний пример `admin/post-comment` показывает каким образом вы можете расположить контроллер в подпапке
|
||||
[[yii\base\Application::controllerNamespace|пространства имен контроллеров]]. Это очень удобно, когда вы хотите организовать свои контроллеры
|
||||
в несколько категорий и не хотите использовать [модули](structure-modules.md).
|
||||
|
||||
|
||||
@ -64,10 +64,6 @@ $config = require(__DIR__ . '/../config/web.php');
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi не имеет констант STDIN и STDOUT, они определяются по умолчанию
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// регистрация загрузчика классов Composer
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -69,10 +69,6 @@ yii migrate/up 5 --migrationTable=migrations
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
|
||||
|
||||
|
||||
@ -141,10 +141,10 @@ class SiteController extends Controller
|
||||
|
||||
Класи контролерів мають бути [автоматично завантаженими](concept-autoloading.md). Саме з цієї причини у вищенаведених прикладах
|
||||
контролер `article` має бути збереженим у файл, [псевдонім шляху](concept-aliases.md) якого є
|
||||
`@app/controllers/ArticleController.php`; в той час, як контролер `admin/post2-comment` має знаходитись у файлі
|
||||
`@app/controllers/admin/Post2CommentController.php`.
|
||||
`@app/controllers/ArticleController.php`; в той час, як контролер `admin/post-comment` має знаходитись у файлі
|
||||
`@app/controllers/admin/PostCommentController.php`.
|
||||
|
||||
> Інформація: Останній приклад `admin/post2-comment` показує яким чином ви можете розташувати контролер в під-директорії
|
||||
> Інформація: Останній приклад `admin/post-comment` показує яким чином ви можете розташувати контролер в під-директорії
|
||||
[[yii\base\Application::controllerNamespace|простору імен контролера]]. Це дуже зручно, коли ви хочете організувати
|
||||
свої контролери у декілька категорій і не хочете використовувати [модулі](structure-modules.md).
|
||||
|
||||
|
||||
@ -64,10 +64,6 @@ $config = require(__DIR__ . '/../config/web.php');
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi не має констант STDIN та STDOUT за замовчуванням
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// реєстрація автозавантажувача класів Composer
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -69,10 +69,6 @@ yii migrate/up 5 --migrationTable=migrations
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
|
||||
|
||||
|
||||
@ -135,9 +135,9 @@ ID контроллеров также могут содержать префи
|
||||
|
||||
Классы контроллеров должны быть [автозагружаемыми](concept-autoloading.md). Именно по этой причине, в вышеприведенном примере,
|
||||
контроллер `article` должен быть сохранен в файл, [псевдоним](concept-aliases.md) которого `@app/controllers/ArticleController.php`;
|
||||
в то время как контроллер `admin/post2-comment` должен находиться в файле `@app/controllers/admin/Post2CommentController.php`.
|
||||
в то время как контроллер `admin/post-comment` должен находиться в файле `@app/controllers/admin/PostCommentController.php`.
|
||||
|
||||
> Информация: Последний пример `admin/post2-comment` показывает каким образом вы можете расположить контроллер в подпапке
|
||||
> Информация: Последний пример `admin/post-comment` показывает каким образом вы можете расположить контроллер в подпапке
|
||||
[[yii\base\Application::controllerNamespace|пространства имен контроллеров]]. Это очень удобно, когда вы хотите организовать свои контроллеры
|
||||
в несколько категорий и не хотите использовать [модули](structure-modules.md).
|
||||
|
||||
|
||||
@ -107,7 +107,7 @@ class User extends ActiveRecord implements IdentityInterface
|
||||
如果认证失败,会发送一个HTTP状态码为401的响应,并带有其他相关信息头(如HTTP 基本认证会有`WWW-Authenticate` 头信息).
|
||||
|
||||
|
||||
## 授权 <a name="authorization"></a>
|
||||
## 授权 <span id="authorization"></span>
|
||||
|
||||
在用户认证成功后,你可能想要检查他是否有权限执行对应的操作来获取资源,这个过程称为 *authorization* ,
|
||||
详情请参考 [Authorization section](security-authorization.md).
|
||||
|
||||
@ -21,7 +21,7 @@ Yii 提供两个控制器基类来简化创建RESTful 操作的工作:[[yii\rest
|
||||
* 对操作和资源进行用户认证.
|
||||
|
||||
|
||||
## 创建控制器类 <a name="creating-controller"></a>
|
||||
## 创建控制器类 <span id="creating-controller"></span>
|
||||
|
||||
当创建一个新的控制器类,控制器类的命名最好使用资源名称的单数格式,例如,提供用户信息的控制器
|
||||
可命名为`UserController`.
|
||||
@ -38,7 +38,7 @@ public function actionView($id)
|
||||
```
|
||||
|
||||
|
||||
## 过滤器 <a name="filters"></a>
|
||||
## 过滤器 <span id="filters"></span>
|
||||
|
||||
[[yii\rest\Controller]]提供的大多数RESTful API功能通过[过滤器](structure-filters.md)实现.
|
||||
特别是以下过滤器会按顺序执行:
|
||||
@ -67,13 +67,13 @@ public function behaviors()
|
||||
```
|
||||
|
||||
|
||||
## 继承 `ActiveController` <a name="extending-active-controller"></a>
|
||||
## 继承 `ActiveController` <span id="extending-active-controller"></span>
|
||||
|
||||
如果你的控制器继承[[yii\rest\ActiveController]],应设置[[yii\rest\ActiveController::modelClass||modelClass]] 属性
|
||||
为通过该控制器返回给用户的资源类名,该类必须继承[[yii\db\ActiveRecord]].
|
||||
|
||||
|
||||
### 自定义操作 <a name="customizing-actions"></a>
|
||||
### 自定义操作 <span id="customizing-actions"></span>
|
||||
|
||||
[[yii\rest\ActiveController]] 默认提供一下操作:
|
||||
|
||||
@ -110,7 +110,7 @@ public function prepareDataProvider()
|
||||
请参考独立操作类的参考文档学习哪些配置项有用。
|
||||
|
||||
|
||||
### 执行访问检查 <a name="performing-access-check"></a>
|
||||
### 执行访问检查 <span id="performing-access-check"></span>
|
||||
|
||||
通过RESTful APIs显示数据时,经常需要检查当前用户是否有权限访问和操作所请求的资源,
|
||||
在[[yii\rest\ActiveController]]中,可覆盖[[yii\rest\ActiveController::checkAccess()|checkAccess()]]方法来完成权限检查。
|
||||
|
||||
@ -41,3 +41,54 @@ Content-Type: application/json; charset=UTF-8
|
||||
* `422`: 数据验证失败 (例如,响应一个 `POST` 请求)。 请检查响应体内详细的错误消息。
|
||||
* `429`: 请求过多。 由于限速请求被拒绝。
|
||||
* `500`: 内部服务器错误。 这可能是由于内部程序错误引起的。
|
||||
|
||||
|
||||
## 自定义错误响应 <span id="customizing-error-response"></span>
|
||||
|
||||
有时你可能想自定义默认的错误响应格式。例如,你想一直使用HTTP状态码200,
|
||||
而不是依赖于使用不同的HTTP状态来表示不同的错误,
|
||||
并附上实际的HTTP状态代码为JSON结构的一部分的响应,就像以下所示,
|
||||
|
||||
```
|
||||
HTTP/1.1 200 OK
|
||||
Date: Sun, 02 Mar 2014 05:31:43 GMT
|
||||
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
|
||||
Transfer-Encoding: chunked
|
||||
Content-Type: application/json; charset=UTF-8
|
||||
|
||||
{
|
||||
"success": false,
|
||||
"data": {
|
||||
"name": "Not Found Exception",
|
||||
"message": "The requested resource was not found.",
|
||||
"code": 0,
|
||||
"status": 404
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
为了实现这一目的,你可以响应该应用程序配置的 `response` 组件的 `beforeSend` 事件:
|
||||
|
||||
```php
|
||||
return [
|
||||
// ...
|
||||
'components' => [
|
||||
'response' => [
|
||||
'class' => 'yii\web\Response',
|
||||
'on beforeSend' => function ($event) {
|
||||
$response = $event->sender;
|
||||
if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) {
|
||||
$response->data = [
|
||||
'success' => $response->isSuccessful,
|
||||
'data' => $response->data,
|
||||
];
|
||||
$response->statusCode = 200;
|
||||
}
|
||||
},
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
当 `suppress_response_code` 作为 `GET` 参数传递时,上面的代码
|
||||
将重新按照自己定义的格式响应(无论失败还是成功)。
|
||||
|
||||
@ -60,6 +60,23 @@ class UserController extends ActiveController
|
||||
用户的数据就能通过美化的 URL 和有意义的 http 动词进行访问和操作。
|
||||
|
||||
|
||||
## 启用 JSON 输入 <span id="enabling-json-input"></span>
|
||||
|
||||
为了使 API 接收 JSON 格式的输入数据,配置 `request` 应用程序组件的 [[yii\web\Request::$parsers|parsers]]
|
||||
属性使用 [[yii\web\JsonParser]] 用于JSON输入:
|
||||
|
||||
```php
|
||||
'request' => [
|
||||
'parsers' => [
|
||||
'application/json' => 'yii\web\JsonParser',
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||
> 补充:上述配置是可选的。若未按上述配置,API 将仅可以分辨
|
||||
`application/x-www-form-urlencoded` 和 `multipart/form-data` 输入格式。
|
||||
|
||||
|
||||
## 尝试 <span id="trying-it-out"></span>
|
||||
|
||||
随着以上所做的最小的努力,你已经完成了创建用于访问用户数据
|
||||
@ -76,16 +93,15 @@ class UserController extends ActiveController
|
||||
* `OPTIONS /users/123`: 显示有关末端 `/users/123` 支持的动词
|
||||
|
||||
> 补充:Yii 将在末端使用的控制器的名称自动变为复数。(译注:个人感觉这里应该变为注意)
|
||||
> 你可以用 [[yii\rest\UrlRule::$pluralize]]-属性来配置此项。
|
||||
|
||||
你可以访问你的API用`curl`命令如下,
|
||||
你可以访问你的API用 `curl` 命令如下,
|
||||
|
||||
```
|
||||
$ curl -i -H "Accept:application/json" "http://localhost/users"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Date: Sun, 02 Mar 2014 05:31:43 GMT
|
||||
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
|
||||
X-Powered-By: PHP/5.4.20
|
||||
...
|
||||
X-Pagination-Total-Count: 1000
|
||||
X-Pagination-Page-Count: 50
|
||||
X-Pagination-Current-Page: 1
|
||||
@ -109,15 +125,14 @@ Content-Type: application/json; charset=UTF-8
|
||||
]
|
||||
```
|
||||
|
||||
试着改变可接受的内容类型为`application/xml`,你会看到结果以 XML 格式返回:
|
||||
试着改变可接受的内容类型为`application/xml`,
|
||||
你会看到结果以 XML 格式返回:
|
||||
|
||||
```
|
||||
$ curl -i -H "Accept:application/xml" "http://localhost/users"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Date: Sun, 02 Mar 2014 05:31:43 GMT
|
||||
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
|
||||
X-Powered-By: PHP/5.4.20
|
||||
...
|
||||
X-Pagination-Total-Count: 1000
|
||||
X-Pagination-Page-Count: 50
|
||||
X-Pagination-Current-Page: 1
|
||||
@ -142,6 +157,20 @@ Content-Type: application/xml
|
||||
</response>
|
||||
```
|
||||
|
||||
以下命令将创建一个新的用户通过发送JSON格式的用户数据的 POST 请求:
|
||||
|
||||
```
|
||||
$ curl -i -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://localhost/users" -d '{"username": "example", "email": "user@example.com"}'
|
||||
|
||||
HTTP/1.1 201 Created
|
||||
...
|
||||
Location: http://localhost/users/1
|
||||
Content-Length: 99
|
||||
Content-Type: application/json; charset=UTF-8
|
||||
|
||||
{"id":1,"username":"example","email":"user@example.com","created_at":1414674789,"updated_at":1414674789}
|
||||
```
|
||||
|
||||
> 技巧:你还可以通过 Web 浏览器中输入 URL `http://localhost/users` 来访问你的 API。
|
||||
尽管如此,你可能需要一些浏览器插件来发送特定的 headers 请求。
|
||||
|
||||
@ -169,5 +198,6 @@ Content-Type: application/xml
|
||||
|
||||
你可以使用 [[yii\rest\UrlRule]] 简化路由到你的 API 末端。
|
||||
|
||||
为了方便维护你的WEB前端和后端,建议你开发接口作为一个单独的应用程序,虽然这不是必须的。
|
||||
为了方便维护你的WEB前端和后端,建议你开发接口作为一个单独的应用程序,
|
||||
虽然这不是必须的。
|
||||
|
||||
|
||||
@ -15,7 +15,7 @@ RESTful 的 API 都是关于访问和操作 *资源*,可将资源看成MVC模
|
||||
继承 [[yii\base\Model]] 会将它所有的公开成员变量返回。
|
||||
|
||||
|
||||
## 字段 <a name="fields"></a>
|
||||
## 字段 <span id="fields"></span>
|
||||
|
||||
当RESTful API响应中包含一个资源时,该资源需要序列化成一个字符串。
|
||||
Yii将这个过程分成两步,首先,资源会被[[yii\rest\Serializer]]转换成数组,
|
||||
@ -42,7 +42,7 @@ http://localhost/users?fields=id,email&expand=profile
|
||||
```
|
||||
|
||||
|
||||
### 覆盖 `fields()` 方法 <a name="overriding-fields"></a>
|
||||
### 覆盖 `fields()` 方法 <span id="overriding-fields"></span>
|
||||
|
||||
[[yii\base\Model::fields()]] 默认返回模型的所有属性作为字段,
|
||||
[[yii\db\ActiveRecord::fields()]] 只返回和数据表关联的属性作为字段。
|
||||
@ -83,7 +83,7 @@ public function fields()
|
||||
> 应覆盖`fields()`过滤掉,在上述例子中,我们选择过滤掉 `auth_key`, `password_hash` 和 `password_reset_token`.
|
||||
|
||||
|
||||
### 覆盖 `extraFields()` 方法 <a name="overriding-extra-fields"></a>
|
||||
### 覆盖 `extraFields()` 方法 <span id="overriding-extra-fields"></span>
|
||||
|
||||
[[yii\base\Model::extraFields()]] 默认返回空值,[[yii\db\ActiveRecord::extraFields()]] 返回和数据表关联的属性。
|
||||
|
||||
@ -119,7 +119,7 @@ public function extraFields()
|
||||
```
|
||||
|
||||
|
||||
## 链接 <a name="links"></a>
|
||||
## 链接 <span id="links"></span>
|
||||
|
||||
[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), 是Hypermedia as the Engine of Application State的缩写,
|
||||
提升RESTful API 应返回允许终端用户访问的资源操作的信息,HATEOAS 的目的是在API中返回包含相关链接信息的资源数据。
|
||||
@ -160,7 +160,7 @@ class User extends ActiveRecord implements Linkable
|
||||
```
|
||||
|
||||
|
||||
## 集合 <a name="collections"></a>
|
||||
## 集合 <span id="collections"></span>
|
||||
|
||||
资源对象可以组成 *集合*,每个集合包含一组相同类型的资源对象。
|
||||
|
||||
|
||||
@ -129,9 +129,9 @@ class SiteController extends Controller
|
||||
|
||||
控制器类必须能被 [自动加载](concept-autoloading.md),所以在上面的例子中,
|
||||
控制器`article` 类应在 [别名](concept-aliases.md) 为`@app/controllers/ArticleController.php`的文件中定义,
|
||||
控制器`admin/post2-comment`应在`@app/controllers/admin/Post2CommentController.php`文件中。
|
||||
控制器`admin/post-comment`应在`@app/controllers/admin/PostCommentController.php`文件中。
|
||||
|
||||
> 补充: 最后一个示例 `admin/post2-comment` 表示你可以将控制器放在
|
||||
> 补充: 最后一个示例 `admin/post-comment` 表示你可以将控制器放在
|
||||
[[yii\base\Application::controllerNamespace|controller namespace]]控制器命名空间下的子目录中,
|
||||
在你不想用 [模块](structure-modules.md) 的情况下给控制器分类,这种方式很有用。
|
||||
|
||||
|
||||
@ -58,10 +58,6 @@ $config = require(__DIR__ . '/../config/web.php');
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi 默认没有定义 STDIN 和 STDOUT
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// 注册 Composer 自动加载器
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -64,10 +64,6 @@ Similarly, the following is the code for the entry script of a console applicati
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
// register Composer autoloader
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
|
||||
|
||||
@ -69,10 +69,6 @@ It contains code like the following:
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
require(__DIR__ . '/vendor/autoload.php');
|
||||
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
|
||||
|
||||
|
||||
@ -93,7 +93,7 @@ class BaseYii
|
||||
*/
|
||||
public static function getVersion()
|
||||
{
|
||||
return '2.0.5-dev';
|
||||
return '2.0.6-dev';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
Yii Framework 2 Change Log
|
||||
==========================
|
||||
|
||||
2.0.5 under development
|
||||
2.0.6 under development
|
||||
-----------------------
|
||||
|
||||
- Bug #7305: Logging of Exception objects resulted in failure of the logger i.e. no logs being written (cebe)
|
||||
@ -24,12 +24,12 @@ Yii Framework 2 Change Log
|
||||
- Bug #8772: ActiveQuery failed removing duplicate records after join when the resultset did not contain the pk values e.g. after grouping (cebe)
|
||||
- Bug #8900: Fixed determine active menu item with url-alias in route `\yii\widgets\Menu::isItemActive()` (demi)
|
||||
- Bug #9046: Fixed problem with endless error loop when an error occurred after sending a stream or file download response to the user (cebe)
|
||||
- Bug #9070: Fixed `ViewAction::resolveViewName()` not to accept `/../` and `/./` (thejahweh, samdark)
|
||||
- Bug: Fixed string comparison in `BaseActiveRecord::unlink()` which may result in wrong comparison result for hash valued primary keys starting with `0e` (cebe)
|
||||
- Bug: Pass correct action name to `yii\console\Controller::options()` when default action was requested (cebe)
|
||||
- Bug: Automatic garbage collection in `yii\caching\FileCache` was not triggered (kidol)
|
||||
- Enh #3335: Implemented `SchemaBuilder` (pana1990, vaseninm, samdark)
|
||||
- Enh #6043: Specification for 'class' and 'style' in array format added to `yii\helpers\Html` (klimov-paul)
|
||||
- Enh #6853: Console application will now register PHP constants for `STDIN`, `STDOUT`, and `STDERR` itself if they are not defined (cebe)
|
||||
- Enh #7169: `yii\widgets\ActiveField` now uses corresponding methods for default parts rendering (klimov-paul)
|
||||
- Enh #8070: `yii\console\controllers\MessageController` now sorts created messages, even if there is no new one, while saving to PHP file (klimov-paul)
|
||||
- Enh #8286: `yii\console\controllers\MessageController` improved allowing extraction of nested translator calls (klimov-paul)
|
||||
@ -46,6 +46,13 @@ Yii Framework 2 Change Log
|
||||
- Chg #6354: `ErrorHandler::logException()` will now log the whole exception object instead of only its string representation (cebe)
|
||||
- Chg #8556: Extracted `yii\web\User::getAuthManager()` method (samdark)
|
||||
|
||||
|
||||
2.0.5 July 11, 2015
|
||||
-------------------
|
||||
|
||||
- Bug #9070 (CVE-2015-5467): Fixed `ViewAction::resolveViewName()` not to accept `/../` and `/./` (thejahweh, samdark)
|
||||
|
||||
|
||||
2.0.4 May 10, 2015
|
||||
------------------
|
||||
|
||||
|
||||
@ -5,11 +5,11 @@ Upgrading Instructions for Yii Framework v2
|
||||
|
||||
The following upgrading instructions are cumulative. That is,
|
||||
if you want to upgrade from version A to version C and there is
|
||||
version B between A and C, you need to following the instructions
|
||||
version B between A and C, you need to follow the instructions
|
||||
for both A and B.
|
||||
|
||||
|
||||
Upgrade from Yii 2.0.4
|
||||
Upgrade from Yii 2.0.5
|
||||
----------------------
|
||||
|
||||
* The signature of the following methods in `yii\console\controllers\MessageController` has changed. They have an extra parameter `$markUnused`.
|
||||
@ -18,6 +18,11 @@ Upgrade from Yii 2.0.4
|
||||
- `saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)`
|
||||
- `saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)`
|
||||
|
||||
Upgrade from Yii 2.0.4
|
||||
----------------------
|
||||
|
||||
Upgrading from 2.0.4 to 2.0.5 does not require any changes.
|
||||
|
||||
Upgrade from Yii 2.0.3
|
||||
----------------------
|
||||
|
||||
|
||||
@ -112,7 +112,7 @@ class FileCache extends Cache
|
||||
$fp = @fopen($cacheFile, 'r');
|
||||
if ($fp !== false) {
|
||||
@flock($fp, LOCK_SH);
|
||||
$cacheValue = @file_get_contents($cacheFile);
|
||||
$cacheValue = @stream_get_contents($fp);
|
||||
@flock($fp, LOCK_UN);
|
||||
@fclose($fp);
|
||||
return $cacheValue;
|
||||
|
||||
@ -10,6 +10,12 @@ namespace yii\console;
|
||||
use Yii;
|
||||
use yii\base\InvalidRouteException;
|
||||
|
||||
// define STDIN, STDOUT and STDERR if the PHP SAPI did not define them (e.g. creating console application in web env)
|
||||
// http://php.net/manual/en/features.commandline.io-streams.php
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
defined('STDERR') or define('STDERR', fopen('php://stderr', 'w'));
|
||||
|
||||
/**
|
||||
* Application represents a console application.
|
||||
*
|
||||
|
||||
@ -10,10 +10,6 @@
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true);
|
||||
|
||||
// fcgi doesn't have STDIN and STDOUT defined by default
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
|
||||
|
||||
$composerAutoload = [
|
||||
__DIR__ . '/../vendor/autoload.php', // in yii2-dev repo
|
||||
__DIR__ . '/../../autoload.php', // installed as a composer binary
|
||||
|
||||
Reference in New Issue
Block a user