首先做一下接口的 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的更多相关文章

  1. YII实现restful,postman进行接口测试

    Yii2 restful API文档 一.配置模块: 1.Config/main.php: 2.创建模块目录: 3.Module.php: 二.路由配置: 三.控制器: 四.Models: 五.测试: ...

  2. Yii2 restful api创建,认证授权以及速率控制

    Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...

  3. yii restful和一般路由共存

    <?php namespace app\controllers; use Yii; use yii\rest\ActiveController; /** * */ class TestContr ...

  4. yii中的restful方式输出并调用接口和判断用户是否登录状态

    //创建一个控制器接口 返回的是restful方式 <?php namespace frontend\controllers; use frontend\models\Fenlei; use f ...

  5. Yii框架实现restful 接口调用,增删改查

    创建模块modules; 在main.php中配置文件:(1) (2)控制器层: namespace frontend\modules\v1\controllers;use frontend\modu ...

  6. Yii restful api跨域

    问题:NO 'Access-Control_Allow-Origin' header is present on the requested resource. 解决方案 <?php names ...

  7. Yii 2.x RESTful 应用 - 类图

    配置url管理器配置请求数据解析器配置用户控制器 ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']

  8. yII中利用urlManager将URL改写成restful风格 这里主要涉及url显示样式

    1.打开config文件夹下面的mian.php   2.修改内容   如把地址http://www.test.com/index.php?r=site/page/sid/1修改为http://www ...

  9. Yii Restful api认证

随机推荐

  1. phpize php扩展模块安装

    安装(fastcgi模式)的时候,常常有这样一句命令:/usr/local/webserver/php/bin/phpize一.phpize是干嘛的?phpize是什么东西呢?php官方的说明:htt ...

  2. 命令行创建Android应用,生成签名,对APK包签名并编译运行

    一.命令行创建Android应用 android create project -n HelloWorld -t android-22 -p HelloWorld1 -k org.crazyit.he ...

  3. python内置函数大全

    一.数学运算类 abs(x) 求绝对值1.参数可以是整型,也可以是复数2.若参数是复数,则返回复数的模 complex([real[, imag]]) 创建一个复数 divmod(a, b) 分别取商 ...

  4. while循环语句

    while(循环条件,返回布尔类型)            {                代码执行的操作,或者打印输出. } do  whilw循环 do            {         ...

  5. android apk 防止反编译技术第一篇-加壳技术

    做android framework方面的工作将近三年的时间了,现在公司让做一下android apk安全方面的研究,于是最近就在网上找大量的资料来学习.现在将最近学习成果做一下整理总结.学习的这些成 ...

  6. Mysql 冷备份批处理

    @Rem Generate today date @echo wscript.echo dateadd("d",0,date)>GetOldDate.vbs @for /f ...

  7. cocos2d-x实战 C++卷 学习笔记--第5章 精灵

    前言: 精灵类是Sprite类.它的子类有PhysicsSprite 和 Skin. PhysicsSprite 是物理引擎精灵类,而Skin是皮肤精灵类,用于骨骼动画. 创建Sprite精灵对象 创 ...

  8. Windows 7 Shortcuts (完整兼具分类有序,想我所想,赞!)

    Original Link: http://www.shortcutworld.com/en/win/Windows_7.html Table of Contents: Managing 'Windo ...

  9. asp.net弹出框后页面走样

    1.去掉language='javascript' ,问题依旧 2.后面加上Response.Write("<script>document.location=document. ...

  10. HPDL380G8平台11.2.0.3 RAC实施手册

    HPDL380G8平台11.2.0.3 RAC实施手册   1 前言 此文档详细描述了Oracle 11gR2 数据库在HPDL380G上的安装RAC的检查及安装步骤.文档中#表示root用户执行,$ ...