通过重写field()和extraFields()方法,可以定义可以将哪些数据放入响应中。这两种方法的区别在于,前者定义了默认字段集,应将其包含在响应中,而后者则定义其他字段,如果最终用户通过expand query参数请求它们,则可以将其包含在响应中。
步骤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请求。Location标头包含指向新创建的资源的URL。
- 204-请求已成功处理,响应中不包含任何内容。
- 304-资源未修改。
- 400-错误的请求。
- 401-身份验证失败。
- 403-不允许通过身份验证的用户访问指定的API端点。
- 404-资源不存在。
- 405-不允许使用方法。
- 415-不支持的媒体类型。
- 422-数据验证失败。
- 429-请求太多。
- 500-内部服务器错误。
作者:terry,如若转载,请注明出处:https://www.web176.com/yii/388.html