Yii 实现restful
首先做一下接口的 URL 规划,假设我们要面对的资源是 item ,现在我们暴露5个接口供其他应用调用,分别是:
对于所有 item 列表调用: GET /rest/item
对于某个 item 信息调用: GET /rest/item/(\d+)
创建一个 item: POST /rest/item
更新一个 item: PUT /rest/item/(\d+)
删除一个 item: DELETE /rest/item/(\d+)
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array( //restful routers array('rest/list','pattern'=>'rest/item','verb'=>'GET'),
array('rest/view','pattern'=>'rest/item/<id:\d+>','verb'=>'GET'),
array('rest/create','pattern'=>'rest/item','verb'=>'POST'),
array('rest/update','pattern'=>'rest/item/<id:\d+>','verb'=>'PUT'),
array('rest/delete','pattern'=>'rest/item/<id:\d+>','verb'=>'GET'), ),
),
url配置请看:http://www.cnblogs.com/youxin/p/3870547.html
http://www.cnblogs.com/jshen/p/3732193.html
然后开始编写 REST 的 Controller,安装 yii 框架的约定,我们建立 protected/controllers/RestController.php ,文件内容结构如下:
class RestController extends Controller
{
// Actions
public function actionList()
{
}
public function actionView()
{
}
public function actionCreate()
{
}
public function actionUpdate()
{
}
public function actionDelete()
{
}
// Assistant Functions
private function _sendResponse()
{
}
private function _getStatusCodeMessage()
{
}
}
实现:
<?php
class RestController extends Controller
{
//actions
public function actionList()
{
$items=Post::model()->findAll();//返回的是CActiveRecord[]
if(empty($items))
{
$this->_sendResponse(200,"No items");
}
else
{
$rows=array();
foreach($items as $item)
{
$rows[]=$item->attributes;//attributes Returns all column attribute values.
}
$this->_sendResponse(200,CJson::encode($rows));
} }
public function actionView()
{
if(!isset($_GET['id']))
{
$this->_sendResponse(500,"Item Id is missing");
}
$item=Post::model()->findByPk($_GET['id']);
if(is_null($item))
$this->_sendResponse(404,"No item");
else
$this->_sendResponse(200,CJson::encode($item->attributes)); }
public function actionCreate()
{
$item=new Post();
foreach($_POST as $var=>$value)
{
if($item->hasAttribute($var))
$item->$var=$value;
else
$this->_sendResponse(500,"Paramter Error");
}
if($item->save())
$this->_sendResponse(200,CJson::encode($item));
else
$this->_sendResponse(500,"Could not create Item"); }
public function actionUpdate()
{
//获取 put 方法所带来的 json 数据
$json = file_get_contents('php://input');
$put_vars = CJSON::decode($json,true); $item = Post::model()->findByPk($_GET['id']); if(is_null($item))
$this->_sendResponse(400, 'No Item found'); foreach($put_vars as $var=>$value)
{
if($item->hasAttribute($var))
$item->$var = $value;
else
$this->_sendResponse(500, 'Parameter Error');
} if($item->save())
$this->_sendResponse(200, CJson::encode($item));
else
$this->_sendResponse(500, 'Could not Update Item');
} public function actionDelete()
{
$item = Post::model()->findByPk($_GET['id']);
if(is_null($item))
$this->_sendResponse(400, 'No Item found');
if($item->delete())
$this->_sendResponse(200, 'Delete Success');
else
$this->_sendResponse(500, 'Could not Delete Item');
} private function _sendResponse($status,$body='',$content_type='text/html')
{
$status_header='HTTP/1.1 '.$status.' '.$this->_getStatusCodeMessage($status);
header($status_header);
header("Content-type: ".$content_type);
echo $body;
Yii::app()->end();
}
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篇文章:
http://www.nonb.cn/blog/yii-rest.html
http://www.cnblogs.com/ziyouchutuwenwu/p/3436415.html
http://www.yiiframework.com/forum/index.php?/topic/18412-new-yii-rest-tutorial/
http://stackoverflow.com/questions/6427904/restful-server-design-in-yii
http://www.yiiwiki.com/post/38
http://blog.csdn.net/myweishanli/article/details/17475397
Yii 实现restful的更多相关文章
- YII实现restful,postman进行接口测试
Yii2 restful API文档 一.配置模块: 1.Config/main.php: 2.创建模块目录: 3.Module.php: 二.路由配置: 三.控制器: 四.Models: 五.测试: ...
- Yii2 restful api创建,认证授权以及速率控制
Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...
- yii restful和一般路由共存
<?php namespace app\controllers; use Yii; use yii\rest\ActiveController; /** * */ class TestContr ...
- yii中的restful方式输出并调用接口和判断用户是否登录状态
//创建一个控制器接口 返回的是restful方式 <?php namespace frontend\controllers; use frontend\models\Fenlei; use f ...
- Yii框架实现restful 接口调用,增删改查
创建模块modules; 在main.php中配置文件:(1) (2)控制器层: namespace frontend\modules\v1\controllers;use frontend\modu ...
- Yii restful api跨域
问题:NO 'Access-Control_Allow-Origin' header is present on the requested resource. 解决方案 <?php names ...
- Yii 2.x RESTful 应用 - 类图
配置url管理器配置请求数据解析器配置用户控制器 ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
- yII中利用urlManager将URL改写成restful风格 这里主要涉及url显示样式
1.打开config文件夹下面的mian.php 2.修改内容 如把地址http://www.test.com/index.php?r=site/page/sid/1修改为http://www ...
- Yii Restful api认证
随机推荐
- 解决某些手机RadioGroup中的RadioButton不居中的问题
问题:RadioButton中使用android:gravity="center"使其图片文字居中,在我的华为荣耀7手机上居中显示了,但在HUAWEI G606-T00却显示在右侧 ...
- 用 CSS 隐藏页面元素的 5 种方法
原文链接:用 CSS 隐藏页面元素的 5 种方法,转载请注明来源! 用 CSS 隐藏页面元素有许多种方法.你可以将 opacity 设为 0.将 visibility 设为 hidden.将 disp ...
- Java多线程--同步函数
/*需求:银行有一个金库有两个储户分别存300元 每次存100元,存3次 目的:该程序是否有安全问题,如果有,如何解决? 如何找问题(很重要)1.明确哪些代码是多线程运行代码2.明确共享数据3.明确多 ...
- Java多线程练习:ticket卖票程序
/*需求:简单的卖票程序多个窗口买票 */ class Ticket extends Thread{ private static int tick=100; public void ru ...
- 关于C++对汉字拼音的处理——终结篇(补充)
需要补充的有三个方面: 1.新华字典数据获取方法1: 点击这里 2.新华字典数据获取方法2: 点击这里 3.比较稳定的其它的汉字转拼音的方法: 点击这里 *注:由于内容较多3个部分分文3篇博客进行分别 ...
- sgu 101 domino
题意还算简洁明了,加上有道翻译凑过着读完了题.题意大体上是 给你 n 个多米诺骨牌, 给出每个骨牌两端的数字, 只有数字相同才可以推到, 比如 2-3和3-2.你可以旋转这些多米诺骨牌, 输出一个可以 ...
- 模板:函数memset
需要的头文件 <memory.h> or <string.h> memset 函数介绍 void *memset(void *s, int ch, size_t n); 函 ...
- RabbitMQ远程访问配置
1 首先创建一个新的账户 并给上Administrator标签 2然后给这个新账户添加虚拟主机访问权限 3在windows 下的 rabbitmq安装文件下的etc文件下的配置文件添加以下 [ ...
- Redhat 6.5 x64 下载地址
http://ftp.okhysing.is/ftp/redhat/6.5/isos/x86_64/
- 网页制作常见的面试题(怎样兼容IE6/IE7/火狐浏览器)
1.IE6双边距问题? 在IE6的浏览器中明明设置的是10px的margin却为什么显示的是20px的margin其实这个Ie6的一个双边距BUG例如:<style type="tex ...