首先做一下接口的 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. Oracle Split Partitions

    1. 创建分离分区的存储过程 CREATE OR REPLACE Procedure SP_Split_Partition( v_table_name_in in varchar2, v_part_n ...

  2. NSdata 与 NSString,Byte数组,UIImage 的相互转换

    1. NSData 与 NSString NSData-> NSString NSString *aString = [[NSString alloc] initWithData:adataen ...

  3. ios - 再细读KVO

    [罗国强原创] KVO - Key-Value Observing. 它提供了一种机制,允许对象被通知到其他对象的具体特性的变化.它特别适用于一个应用的模型层与控制层的交互. 一种典型的应用场景是在一 ...

  4. java三线程循环有序打印ABC

    迅雷笔试题: 编写一个程序,开启3个线程,这3个线程的ID分别为A.B.C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示:如:ABCABC….依次递推. 解决思路:每个线 ...

  5. 鸟哥私房菜笔记:Iptables:数据包过滤软件

    数据包进入流程:规则顺序的重要性 iptables利用的是数据包过滤机制,所以它会分析数据包的包头数据.根据包头数据与定义的规则来决定该数据包是否可以进入主机或者是被丢弃.也就是说,根据数据包的分析资 ...

  6. 网站开发常用jQuery插件总结(一)提示插件alertify

    1.alertify插件功能 主要实现提示功能,用于代替js中的alert,confirm,prompt,显示友好的提示框 2.alertify官方地址 http://fabien-d.github. ...

  7. C# partial 说明

    1. 什么是局部类型? C# 2.0 引入了局部类型的概念.局部类型允许我们将一个类.结构或接口分成几个部分,分别实现在几个不同的.cs文件中. 局部类型适用于以下情况: (1) 类型特别大,不宜放在 ...

  8. jquery鼠标样式

    浏览器是有自带的鼠标样式的,如果某些时候为了保持鼠标样式的统一,或者想指定特定的鼠标样式该怎么办呢?那就要使用自定义了,下面有个不错的示例,喜欢的朋友可以参考下   1.浏览器自带的鼠标样式:  2. ...

  9. Asp.net 图片文件防盗链介绍

    想要实现文件放盗链的功能 首先添加一个全局文件 Global.asax 在 Application_BeginRequest中我们可以判断Http报文头中的UrlReferre是否来源本站. if ( ...

  10. PHP 递归创建目录

    /* 用迭代的方法递归创建目录 其实在PHP5.0.0之后mkdir就已经能递归创建目录了. 这里主要是自己学习迭代,所以拿创建级联目录开刀了. 开发中应该写mkdir('./a/b/c/d/e',0 ...