yii2.0 resufulyii2 api接口开发实例怎么写

&>&&>&&>&&>&resful
上传大小:5.84MB
post getdelete
综合评分:0(0位用户评分)
所需积分:1
下载次数:9
审核通过送C币
创建者:ls
创建者:nigelyq
创建者:sinat_
课程推荐相关知识库
上传者其他资源上传者专辑
开发技术热门标签
VIP会员动态
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
android服务器底层网络模块的设计方法
所需积分:0
剩余积分:720
您当前C币:0
可兑换下载积分:0
兑换下载分:
兑换失败,您当前C币不够,请先充值C币
消耗C币:0
你当前的下载分为234。
会员到期时间:
剩余下载次数:
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可奖励20下载分
被举报人:
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:yii2 resetful 授权验证详解
(window.slotbydup=window.slotbydup || []).push({
id: '2611110',
container: s,
size: '240,200',
display: 'inlay-fix'
您当前位置: &
[ 所属分类
作者 红领巾 ]
什么是restful风格的api呢?我们之前有写过大篇的文章来介绍其概念以及基本操作。既然写过了,那今天是要说点什么吗?这篇文章主要针对实际场景中api的部署来写。我们今天就来大大的侃侃那些年api遇到的授权验证问题!独家干活,如果看完有所受益,记得不要忘记给我点赞哦。业务分析我们先来了解一下整个逻辑1.用户在客户端填写登录表单2.用户提交表单,客户端请求登录接口login3.服务端校验用户的帐号密码,并返回一个有效的token给客户端4.客户端拿到用户的token,将之存储在客户端比如cookie中5.客户端携带token访问需要校验的接口比如获取用户个人信息接口6.服务端校验token的有效性,校验通过,反正返回客户端需要的信息,校验失败,需要用户重新登录本文我们以用户登录,获取用户的个人信息为例进行详细的完整版说明。以上,便是我们本篇文章要实现的重点。先别激动,也别紧张,分析好了之后,细节部分我们再一步一个脚印走下去。准备工作1.你应该有一个api应用.2.对于客户端,我们准备采用postman进行模拟,如果你的google浏览器还没有安装postman,请先自行下载3.要测试的用户表需要有一个api_token的字段,没有的请先自行添加,并保证该字段足够长度4.api应用开启了路由美化,并先配置post类型的login操作和get类型的signup-test操作5.关闭了user组件的session会话关于上面准备工作的第4点和第5点,我们贴一下代码方便理解'components' =& [ 'user' =& [
'identityClass' =& 'common\models\User', 'enableAutoLogin' =& true, 'enableSession' =& false, ], 'urlManager' =& [ 'enablePrettyUrl' =& true, 'showScriptName' =& false, 'enableStrictParsing' =& true, 'rules' =& [ [ 'class' =& 'yii\rest\UrlRule', 'controller' =& ['v1/user'], 'extraPatterns' =& [ 'POST login' =& 'login', 'GET signup-test' =& 'signup-test', ] ], ] ], // ......],signup-test操作我们后面添加测试用户,为登录操作提供便利。其他类型的操作后面看需要再做添加。认证类的选择我们在api\modules\v1\controllers\UserController中设定的model类指向 common\models\User类,为了说明重点这里我们就不单独拿出来重写了,看各位需要,有必要的话再单独copy一个User类到api\models下。校验用户权限我们以 yii\filters\auth\QueryParamAuth 为例use yii\filters\auth\QueryParamApublic function behaviors() { return ArrayHelper::merge (parent::behaviors(), [
'authenticator' =& [
'class' =& QueryParamAuth::className()
] );}如此一来,那岂不是所有访问user的操作都需要认证了?那不行,客户端第一个访问login操作的时候哪来的token,yii\filters\auth\QueryParamAuth对外提供一个属性,用于过滤不需要验证的action。我们将UserController的behaviors方法稍作修改public function behaviors() { return ArrayHelper::merge (parent::behaviors(), [
'authenticator' =& [
'class' =& QueryParamAuth::className(), 'optional' =& [ 'login', 'signup-test' ], ]
] );}这样login操作就无需权限验证即可访问了。添加测试用户为了避免让客户端登录失败,我们先写一个简单的方法,往user表里面插入两条数据,便于接下来的校验。&UserController增加signupTest操作,注意此方法不属于讲解范围之内,我们仅用于方便测试。use common\models\U/** * 添加测试用户 */public function actionSignupTest (){ $user = new User(); $user-&generateAuthKey(); $user-&setPassword('123456'); $user-&username = '111'; $user-&email = '; $user-&save(false); return [ 'code' =& 0 ];}如上,我们添加了一个username是111,密码是123456的用户登录操作假设用户在客户端输入用户名和密码进行登录,服务端login操作其实很简单,大部分的业务逻辑处理都在api\models\loginForm上,来先看看login的实现use api\models\LoginF/** * 登录 */public function actionLogin (){ $model = new LoginF $model-&setAttributes(Yii::$app-&request-&post()); if ($user = $model-&login()) { if ($user instanceof IdentityInterface) { return $user-&api_ } else { return $user-& } } else { return $model-& }}登录成功后这里给客户端返回了用户的token,再来看看登录的具体逻辑的实现新建api\models\LoginForm.PHP&&#63namespace api\use Yuse yii\base\Muse common\models\U/** * Login form */class LoginForm extends Model{ public $ public $ private $_ const GET_API_TOKEN = 'generate_api_token'; public function init () { parent::init(); $this-&on(self::GET_API_TOKEN, [$this, 'onGenerateApiToken']); } /** * @inheritdoc * 对客户端表单数据进行验证的rule */ public function rules() { return [ [['username', 'password'], 'required'], ['password', 'validatePassword'], ]; } /** * 自定义的密码认证方法 */ public function validatePassword($attribute, $params) { if (!$this-&hasErrors()) { $this-&_user = $this-&getUser(); if (!$this-&_user || !$this-&_user-&validatePassword($this-&password)) { $this-&addError($attribute, '用户名或密码错误.'); } } } /** * @inheritdoc */ public function attributeLabels() { return [ 'username' =& '用户名', 'password' =& '密码', ]; } /** * Logs in a user using the provided username and password. * * @return boolean whether the user is logged in successfully */ public function login() { if ($this-&validate()) { $this-&trigger(self::GET_API_TOKEN); return $this-&_ } else { } } /** * 根据用户名获取用户的认证信息 * * @return User|null */ protected function getUser() { if ($this-&_user === null) { $this-&_user = User::findByUsername($this-&username); } return $this-&_ } /** * 登录校验成功后,为用户生成新的token * 如果token失效,则重新生成token */ public function onGenerateApiToken () { if (!User::apiTokenIsValid($this-&_user-&api_token)) { $this-&_user-&generateApiToken(); $this-&_user-&save(false); } }}我们回过头来看一下,当我们在UserController的login操作中调用LoginForm的login操作后都发生了什么1、调用LoginForm的login方法2、调用validate方法,随后对rules进行校验3、rules校验中调用validatePassword方法,对用户名和密码进行校验4、validatePassword方法校验的过程中调用LoginForm的getUser方法,通过common\models\User类的findByUsername获取用户,找不到或者common\models\User的validatePassword对密码校验失败则返回error5、触发LoginForm::GENERATE_API_TOKEN事件,调用LoginForm的onGenerateApiToken方法,通过common\models\User的apiTokenIsValid校验token的有效性,如果无效,则调用User的generateApiToken方法重新生成注意common\models\User类必须是用户的认证类.下面补充本节增加的common\models\User的相关方法/** * 生成 api_token */public function generateApiToken(){ $this-&api_token = Yii::$app-&security-&generateRandomString() . '_' . time();}/** * 校验api_token是否有效 */public static function apiTokenIsValid($token){ if (empty($token)) { } $timestamp = (int) substr($token, strrpos($token, '_') + 1); $expire = Yii::$app-&params['user.apiTokenExpire']; return $timestamp + $expire &= time();}继续补充apiTokenIsValid方法中涉及到的token有效期,在api\config\params.php文件内增加即可&?phpreturn [ // ... // token 有效期默认1天 'user.apiTokenExpire' =& 1*24*3600,];到这里呢,客户端登录 服务端返回token给客户端就完成了。按照文中一开始的分析,客户端应该把获取到的token存到本地,比如cookie中。以后再需要token校验的接口访问中,从本地读取比如从cookie中读取并访问接口即可。根据token请求用户的认证操作假设我们已经把获取到的token保存起来了,我们再以访问用户信息的接口为例。yii\filters\auth\QueryParamAuth类认定的token参数是 access-token,我们可以在行为中修改下public function behaviors() { return ArrayHelper::merge (parent::behaviors(), [
'authenticator' =& [
'class' =& QueryParamAuth::className(), 'tokenParam' =& 'token', 'optional' =& [ 'login', 'signup-test' ], ]
] );}这里将默认的access-token修改为token。我们在配置文件的urlManager组件中增加对userProfile操作'extraPatterns' =& [ 'POST login' =& 'login', 'GET signup-test' =& 'signup-test', 'GET user-profile' =& 'user-profile',]我们用postman模拟请求访问下 /v1/users/user-profile?token=apeuT9dAgH072qbfrtihfzL6qDe_l4qz_发现,抛出了一个异常\"findIdentityByAccessToken\" is not implemented.这是怎么回事呢?我们找到 yii\filters\auth\QueryParamAuth 的authenticate方法,发现这里调用了 common\models\User类的loginByAccessToken方法,有同学疑惑了,common\models\User类没实现loginByAccessToken方法为啥说findIdentityByAccessToken方法没实现?如果你还记得common\models\User类实现了yii\web\user类的接口的话,你应该会打开yii\web\User类找答案。没错,loginByAccessToken方法在yii\web\User中实现了,该类中调用了common\models\User的findIdentityByAccessToken,但是我们看到,该方法中通过throw抛出了异常,也就是说这个方法要我们自己手动实现!这好办了,我们就来实现下common\models\User类的findIdentityByAccessToken方法吧public static function findIdentityByAccessToken($token, $type = null){ // 如果token无效的话, if(!static::apiTokenIsValid($token)) { throw new \yii\web\UnauthorizedHttpException("token is invalid."); } return static::findOne(['api_token' =& $token, 'status' =& self::STATUS_ACTIVE]); // throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');}验证完token的有效性,下面就要开始实现主要的业务逻辑部分了。/** * 获取用户信息 */public function actionUserProfile ($token){ // 到这一步,token都认为是有效的了 // 下面只需要实现业务逻辑即可,下面仅仅作为案例,比如你可能需要关联其他表获取用户信息等等 $user = User::findIdentityByAccessToken($token); return [ 'id' =& $user-&id, 'username' =& $user-&username, 'email' =& $user-&email, ];}服务端返回的数据类型定义在postman中我们可以以何种数据类型输出的接口的数据,但是,有些人发现,当我们把postman模拟请求的地址copy到浏览器地址栏,返回的又却是xml格式了,而且我们明明在UserProfile操作中返回的是属组,怎么回事呢?这其实是官方捣的鬼啦,我们一层层源码追下去,发现在yii\rest\Controller类中,有一个 contentNegotiator行为,该行为指定了允许返回的数据格式formats是json和xml,返回的最终的数据格式根据请求头中Accept包含的首先出现在formats中的为准,你可以在yii\filters\ContentNegotiator的negotiateContentType方法中找到答案。你可以在浏览器的请求头中看到Accept:text/html,application/xhtml+xml,application/q=0.9,image/webp,*/*;q=0.8即application/xml首先出现在formats中,所以返回的数据格式是xml类型,如果客户端获取到的数据格式想按照json进行解析,只需要设置请求头的Accept的值等于application/json即可有同学可能要说,这样太麻烦了,啥年代了,谁还用xml,我就想服务端输出json格式的数据,怎么做?办法就是用来解决问题滴,来看看怎么做。api\config\main.php文件中增加对response的配置'response' =& [ 'class' =& 'yii\web\Response', 'on beforeSend' =& function ($event) { $response = $event-& $response-&format = yii\web\Response::FORMAT_JSON; },],如此,不管你客户端传什么,服务端最终输出的都会是json格式的数据了。自定义错误处理机制再来看另外一个比较常见的问题:你看我们上面几个方法哈,返回的结果是各式各样的,这样就给客户端解析增加了困扰,而且一旦有异常抛出,返回的代码还都是一堆一堆的,头疼,怎么办?说到这个问题之前呢,我们先说一下yii中先关的异常处理类,当然,有很多哈。比如下面常见的一些,其他的自己去挖掘yii\web\BadRequestHttpExceptionyii\web\ForbiddenHttpExceptionyii\web\NotFoundHttpExceptionyii\web\ServerErrorHttpExceptionyii\web\UnauthorizedHttpExceptionyii\web\TooManyRequestsHttpException实际开发中各位要善于去利用这些类去捕获异常,抛出异常。说远了哈,我们回到重点,来说如何自定义接口异常响应或者叫自定义统一的数据格式,比如向下面这种配置,统一响应客户端的格式标准。'response' =& [ 'class' =& 'yii\web\Response', 'on beforeSend' =& function ($event) { $response = $event-& $response-&data = [ 'code' =& $response-&getStatusCode(), 'data' =& $response-&data, 'message' =& $response-&statusText ]; $response-&format = yii\web\Response::FORMAT_JSON; },],说道了那么多,本文就要结束了,刚开始接触的同学可能有一些蒙,不要蒙,慢慢消化,先知道这么个意思,了解下restful api接口在整个过程中是怎么用token授权的就好。这样真正实际用到的时候,你也能举一反三!以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师
转载请注明本文标题:本站链接:
分享请点击:
1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
CodeSecTeam微信公众号
人生就像一场舞会,教会你最初舞步的人,却未必能陪你走到散场。
手机客户端调用java rest ful 接口实例
时间: 14:57:49
&&&& 阅读:205
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
HttpWebRequest request = WebRequest.Create("http://192.168.0.99:8080/wzh-webservice/rest/login?username=shuenjia&password=123456") as HttpWebR//rest/login
request.Method = "post";
request.KeepAlive = true;
request.Method = "getUserInfoByNameAndPwd";
request.AllowAutoRedirect = false;
request.ContentType = "application/x-www-form-urlencoded";
byte[] postdatabtyes = Encoding.UTF8.GetBytes("param={\"username\":\"shuenjia\",\"password\":\"123456\"}");
request.ContentLength = postdatabtyes.L
Stream requeststream = request.GetRequestStream();
requeststream.Write(postdatabtyes, 0, postdatabtyes.Length);
requeststream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
resp = sr.ReadToEnd();
HttpWebRequest request = WebRequest.Create("http://") as HttpWebR
request.Credentials = new NetworkCredential("123", "123");
request.Method = "POST";
request.KeepAlive =
request.AllowAutoRedirect =
request.ContentType = "application/x-www-form-urlencoded";
byte[] postdatabtyes = Encoding.UTF8.GetBytes("参数");
request.ContentLength = postdatabtyes.L
Stream requeststream = request.GetRequestStream();
requeststream.Write(postdatabtyes, 0, postdatabtyes.Length);
requeststream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
resp = sr.ReadToEnd();
&标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文:/lijianhua/p/5558740.html
教程昨日排行
&&国之画&&&& &&&&&&
&& &&&&&&&&&&&&&&
鲁ICP备号-4
打开技术之扣,分享程序人生!Building a REST API in Yii2.0 | Wiki | Yii PHP Framework
Documentation
Yii 2.0: Building a REST API in Yii2.0
15 followers
This is wiki page is useful if you are trying to build a customized REST API in Yii2.0
Note: Yii 2 includes a generic REST feature (ActiveController class) that implements a basic REST API for one of your models that you may be able to easily use and not have to write all the below code.
Note:This example is based on the table: user(id(PK AI),name,age,createdAt,updatedAt)
1.Action index
URL: api/user/index
method:GET
"limit":5,
"sort":"id",
"order":false,
"filter":{}
"dateFilter":{"from":"","to":""}
Note1: "page"=&is the current page number
Note2: "limit"=&no.of records in a single page
Note3: "sort"=&sort field(ie this can be id,name,age createdAt or updatedAt)
Note4: "order"=&This can be true/false. true=&ascending order while false=&descending order
Note5: filter=&is a json object to pass any filter elements. eg:{name:'abc',age:20}
"status": 1,
"name": "john",
"age": 78,
"createdAt": " 01:53:31",
"updatedAt": " 01:53:51"
"name": "ben",
"age": 23,
"createdAt": " 01:53:28",
"updatedAt": " 01:54:00"
"name": "rahul",
"age": 72,
"createdAt": " 01:53:25",
"updatedAt": " 01:54:09"
"name": "shafeeque",
"age": 76,
"createdAt": " 01:53:21",
"updatedAt": " 01:54:24"
"name": "sirin",
"age": 73,
"createdAt": " 19:51:49",
"updatedAt": " 01:54:32"
"totalItems": "8"
Action Source code:
public function actionIndex()
$params=$_REQUEST;
$filter=array();
$limit=10;
if(isset($params['page']))
$page=$params['page'];
if(isset($params['limit']))
$limit=$params['limit'];
$offset=$limit*($page-1);
if(isset($params['filter']))
$filter=(array)json_decode($params['filter']);
if(isset($params['datefilter']))
$datefilter=(array)json_decode($params['datefilter']);
if(isset($params['sort']))
$sort=$params['sort'];
if(isset($params['order']))
if($params['order']=="false")
$sort.=" desc";
$sort.=" asc";
$query=new Query;
$query-&offset($offset)
-&limit($limit)
-&from('user')
-&andFilterWhere(['like', 'id', $filter['id']])
-&andFilterWhere(['like', 'name', $filter['name']])
-&andFilterWhere(['like', 'age', $filter['age']])
-&orderBy($sort)
-&select("id,name,age,createdAt,updatedAt");
if($datefilter['from'])
$query-&andWhere("createdAt &= '".$datefilter['from']."' ");
if($datefilter['to'])
$query-&andWhere("createdAt &= '".$datefilter['to']."'");
$command = $query-&createCommand();
$models = $command-&queryAll();
$totalItems=$query-&count();
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&$models,'totalItems'=&$totalItems),JSON_PRETTY_PRINT);
private function setHeader($status)
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this-&_getStatusCodeMessage($status);
$content_type="application/ charset=utf-8";
header($status_header);
header('Content-type: ' . $content_type);
header('X-Powered-By: ' . "Nintriva &&");
private function _getStatusCodeMessage($status)
$codes = Array(
200 =& 'OK',
400 =& 'Bad Request',
401 =& 'Unauthorized',
402 =& 'Payment Required',
403 =& 'Forbidden',
404 =& 'Not Found',
500 =& 'Internal Server Error',
501 =& 'Not Implemented',
return (isset($codes[$status])) ? $codes[$status] : '';
2.Action View
URL: api/user/view/30
method:GET
Note1: "30"=&is the Pk of a record in the user table
"status": 1,
"name": "john",
"age": 78,
"createdAt": " 01:53:31",
"updatedAt": " 01:53:51"
Action Source code:
public function actionView($id)
$model=$this-&findModel($id);
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
protected function findModel($id)
if (($model = User::findOne($id)) !== null) {
return $model;
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'message'=&'Bad request'),JSON_PRETTY_PRINT);
3.Action Create
api/user/create
method:POST
"name":"abc",
"status": 1,
"name": "abc",
"age": "20",
"createdAt": " 02:35:18",
"updatedAt": " 02:35:18"
Action Source code:
public function actionCreate()
$params=$_REQUEST;
$model = new User();
$model-&attributes=$params;
if ($model-&save()) {
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
4.Action Update
URL: api/user/update/32
Note1:"32"=&id(PK) of the record we are going to update
method: POST
"name":"efg",
"status": 1,
"name": "efg",
"age": "25",
"createdAt": " 02:35:18",
"updatedAt": " 02:45:55"
Action Source code:
public function actionUpdate($id)
$params=$_REQUEST;
$model = $this-&findModel($id);
$model-&attributes=$params;
if ($model-&save()) {
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
5.Action Delete
URL: api/user/update/32
method:DELETE
Note1:"32"=&id(PK) of the record we are going to delete
"status": 1,
"name": "efg",
"age": 20,
"createdAt": " 02:40:44",
"updatedAt": " 02:40:44"
Action Source code:
public function actionDelete($id)
$model=$this-&findModel($id);
if($model-&delete())
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
6.Action DeleteAll
Used to delete multiple records at a time.
URL: api/user/deleteall
method:POST
"ids":"[27,28]"
Note1:"ids"=&a list of id(Pk)'s to be deleted
"status": 1,
"name": "shafeeque",
"age": 76,
"createdAt": " 01:53:21",
"updatedAt": " 01:54:24"
"name": "rahul",
"age": 72,
"createdAt": " 01:53:25",
"updatedAt": " 01:54:09"
Action Source code:
public function actionDeleteall()
$ids=json_decode($_REQUEST['ids']);
$data=array();
foreach($ids as $id)
$model=$this-&findModel($id);
if($model-&delete())
$data[]=array_filter($model-&attributes);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&$data),JSON_PRETTY_PRINT);
7.Behaviour to fileter action methods
public function behaviors()
'verbs' =& [
'class' =& VerbFilter::className(),
'actions' =& [
'index'=&['get'],
'view'=&['get'],
'create'=&['post'],
'update'=&['post'],
'delete' =& ['delete'],
'deleteall'=&['post'],
public function beforeAction($event)
$action = $event-&id;
if (isset($this-&actions[$action])) {
$verbs = $this-&actions[$action];
} elseif (isset($this-&actions['*'])) {
$verbs = $this-&actions['*'];
return $event-&isValid;
$verb = Yii::$app-&getRequest()-&getMethod();
$allowed = array_map('strtoupper', $verbs);
if (!in_array($verb, $allowed)) {
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'message'=&'Method not allowed'),JSON_PRETTY_PRINT);
return true;
Controller source code:UserController.php
namespace app\modules\api\controllers;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\db\Query;
class UserController extends Controller
public function behaviors()
'verbs' =& [
'class' =& VerbFilter::className(),
'actions' =& [
'index'=&['get'],
'view'=&['get'],
'create'=&['post'],
'update'=&['post'],
'delete' =& ['delete'],
'deleteall'=&['post'],
public function beforeAction($event)
$action = $event-&id;
if (isset($this-&actions[$action])) {
$verbs = $this-&actions[$action];
} elseif (isset($this-&actions['*'])) {
$verbs = $this-&actions['*'];
return $event-&isValid;
$verb = Yii::$app-&getRequest()-&getMethod();
$allowed = array_map('strtoupper', $verbs);
if (!in_array($verb, $allowed)) {
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'message'=&'Method not allowed'),JSON_PRETTY_PRINT);
return true;
public function actionIndex()
$params=$_REQUEST;
$filter=array();
$limit=10;
if(isset($params['page']))
$page=$params['page'];
if(isset($params['limit']))
$limit=$params['limit'];
$offset=$limit*($page-1);
if(isset($params['filter']))
$filter=(array)json_decode($params['filter']);
if(isset($params['datefilter']))
$datefilter=(array)json_decode($params['datefilter']);
if(isset($params['sort']))
$sort=$params['sort'];
if(isset($params['order']))
if($params['order']=="false")
$sort.=" desc";
$sort.=" asc";
$query=new Query;
$query-&offset($offset)
-&limit($limit)
-&from('user')
-&andFilterWhere(['like', 'id', $filter['id']])
-&andFilterWhere(['like', 'name', $filter['name']])
-&andFilterWhere(['like', 'age', $filter['age']])
-&orderBy($sort)
-&select("id,name,age,createdAt,updatedAt");
if($datefilter['from'])
$query-&andWhere("createdAt &= '".$datefilter['from']."' ");
if($datefilter['to'])
$query-&andWhere("createdAt &= '".$datefilter['to']."'");
$command = $query-&createCommand();
$models = $command-&queryAll();
$totalItems=$query-&count();
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&$models,'totalItems'=&$totalItems),JSON_PRETTY_PRINT);
public function actionView($id)
$model=$this-&findModel($id);
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
public function actionCreate()
$params=$_REQUEST;
$model = new User();
$model-&attributes=$params;
if ($model-&save()) {
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
public function actionUpdate($id)
$params=$_REQUEST;
$model = $this-&findModel($id);
$model-&attributes=$params;
if ($model-&save()) {
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
public function actionDelete($id)
$model=$this-&findModel($id);
if($model-&delete())
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&array_filter($model-&attributes)),JSON_PRETTY_PRINT);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
public function actionDeleteall()
$ids=json_decode($_REQUEST['ids']);
$data=array();
foreach($ids as $id)
$model=$this-&findModel($id);
if($model-&delete())
$data[]=array_filter($model-&attributes);
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'errors'=&$model-&errors),JSON_PRETTY_PRINT);
$this-&setHeader(200);
echo json_encode(array('status'=&1,'data'=&$data),JSON_PRETTY_PRINT);
protected function findModel($id)
if (($model = User::findOne($id)) !== null) {
return $model;
$this-&setHeader(400);
echo json_encode(array('status'=&0,'error_code'=&400,'message'=&'Bad request'),JSON_PRETTY_PRINT);
private function setHeader($status)
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this-&_getStatusCodeMessage($status);
$content_type="application/ charset=utf-8";
header($status_header);
header('Content-type: ' . $content_type);
header('X-Powered-By: ' . "Nintriva &&");
private function _getStatusCodeMessage($status)
$codes = Array(
200 =& 'OK',
400 =& 'Bad Request',
401 =& 'Unauthorized',
402 =& 'Payment Required',
403 =& 'Forbidden',
404 =& 'Not Found',
500 =& 'Internal Server Error',
501 =& 'Not Implemented',
return (isset($codes[$status])) ? $codes[$status] : '';
Happy coding..
Video upload
can you tell me how can i upload a video using POST request?
Overried action
It is great tutorial, but how to override action? I've tried it like this just to test it but it doesn't work
public function actionIndex()
echo json_encode(['test'=&'aaa']);
Suggestions
Wouldn't it be better if you utilized DELETE verb for delete all like this:
DELETE /contacts = delete all
I'll just leave this here.
DEMO REST Yii2 with AngularJS
Yes yii is restful by default..but I was trying to override all actions with all possible api features like sort,pagination and filter needed for my angularjs front end.
Yii2 has native rest api tools.
View current articleView revision
Yii Supporters
Copyright & 2017 by .
All Rights Reserved.

我要回帖

更多关于 yii2 resultful 的文章

 

随机推荐