Yii 字段
通过重写 fields()和extraFields() 方法,您可以定义可以将哪些数据放入响应中。这两种方法的区别在于前者定义了默认的字段集合,这些字段应该包含在响应中,而后者定义附加字段,如果最终用户通过 扩展 查询参数请求它们,则可能包含在响应中。
第1步 - 以 这种方式修改 MyUser 模型。
<?php
namespace app\models;
use app\components\UppercaseBehavior;
use Yii;
/**
* This is the model class for table "user".
*@property integer $id
* @property string $name
* @property string $email
*/
class MyUser extends \yii\db\ActiveRecord {
public function fields() {
return [
'id',
'name',
//PHP callback
'datetime' => function($model) {
return date("d:m:Y H:i:s");
}
];
}
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['name', 'email'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
];
}
}
?>
除了默认字段:id和name之外,我们还添加了一个自定义字段 - datetime 。
第2步 - 在Postman中,运行URL http:// localhost:8080 / users 。

第3步 - 现在,以 这种方式修改 MyUser 模型。
<?php
namespace app\models;
use app\components\UppercaseBehavior;
use Yii;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $name
* @property string $email
*/
class MyUser extends \yii\db\ActiveRecord {
public function fields() {
return [
'id',
'name',
];
}
public function extraFields() {
return ['email'];
}
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['name', 'email'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
];
}
}
?>
请注意,电子邮件字段是由 extraFields() 方法返回的。
第4步 - 要获取该字段的数据,请运行 http:// localhost:8080 / users?expand = email 。

自定义操作
该 警予\其他\ ActiveController 类提供了以下措施-
- 索引 - 逐页列出资源
- 查看 - 返回指定资源的详细信息
- 创建 - 创建一个新资源
- 更新 - 更新现有资源
- 删除 - 删除指定的资源
- 选项 - 返回支持的HTTP方法
以上所有操作均在actions方法()中声明。
要禁用“删除”和“创建”操作,请按照这种方式修改 UserController -
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController {
public $modelClass = 'app\models\MyUser';
public function actions() {
$actions = parent::actions();
// disable the "delete" and "create" actions
unset($actions['delete'], $actions['create']);
return $actions;
}
}
?>
处理错误
当获得RESTful API请求时,如果请求中存在错误或者服务器发生意外事件,则可以简单地引发异常。如果您可以确定错误的原因,则应该引发异常以及适当的HTTP状态码。Yii REST使用以下状态 -
- 200 - 好的。
- 201 - 响应POST请求成功创建资源。 位置标题包含指向新创建的资源的URL。
- 204 - 请求已成功处理,并且响应中不包含任何内容。
- 304 - 资源未被修改。
- 400 - 错误的请求。
- 401 - 认证失败。
- 403 - 已通过身份验证的用户不允许访问指定的API端点。
- 404 - 资源不存在。
- 405 - 方法不允许。
- 415 - 不支持的媒体类型。
- 422 - 数据验证失败。
- 429 - 请求太多。
- 500 - 内部服务器错误。
下一章:Yii 测试
当我们编写一个PHP类时,我们会逐步调试它,或者使用die或echo语句来验证它是如何工作的。如果我们开发一个Web应用程序,我们会在窗体中输入测试数据以确保页面按我们的预期工作。这个测试过程可以自动化。自动测试方法对于长期项 ...
AI 中文社