1、PUT提交,传递参数id必须有值,在body的x-www-from-urllencoded里面传递值
2、POST提交,传递参数不能有值,在body的from-data里面传递值
3、 DELETE, 我没有用自己的删除方法,而是用的默认的
1): 就是你要遵循你的表的要求,去添加元素,例如: 我的表中的mobile是唯一的,所以如果你要是添加重复的话,他会报错的
2): 添加/修改时,他自己默认的是要有场景default的,如果你没有,也是不行的,它默认的是default场景,你可以在你的model类里面添加场景
public function scenarios()
{
return [
'default' => ['mobile', 'username'],
];
}
4: GET查
针对默认的IndexAction方法,如果你仔细看框架里面的源码,你会发现,他有一些是不符合业务逻辑的,例如我们查询信息时,它默认查询所有了,那如果我们不想要查询敏感字段,怎么办?还有,我们想默认只查询没被删除的用户信息,怎么办?这是此时办不到的,那我们在用他自己的方法的同时,给它改变一些,如图所示:
1): 实现只查询未删除的用户
public function actions()
{
$actions = parent::actions();
// 注销系统自带的实现方法
// unset($actions['index'],$actions['create'],$actions['view'],$actions['delete']);
// 自定义数据indexDataProvider覆盖IndexAction中的prepareDataProvider()方法
$actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
return $actions;
}
public function indexDataProvider()
{
/* @var $modelClass \yii\db\BaseActiveRecord */
$modelClass = $this->modelClass;
return new ActiveDataProvider([
'query' => $modelClass::find()->where(['!=', 'status', UserBaseInfo::USER_DEL_STATUS]),
]);
}
2):// 过滤掉一些字段,适用于你希望继承父类实现同时你想屏蔽掉一些敏感字段
public function fields()
{
$fields = parent::fields();
// 删除一些包含敏感信息的字段
unset($fields['password'], $fields['password_salt']);
return $fields;
}
用restful中的内置的一些方法的好处是: 他实现的功能非常多,省去了我们自己要写的方法
如你所见,在 headers 响应,有关于总数,页数的信息,等等。还有一些链接,让你导航到其他页面的数据
你可以访问你的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
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
5: 而对于access-token验证的问题,大家可以看yii2.0官网的http://www.yiichina.com/doc/guide/2.0/rest-authentication,或者之前我看的时候有一个大神的博客:https://github.com/iiYii/yii2-rest-demo/commit/02db1711bcaa42040360d50ffcf771626474f5ad
Comments (0)