首先做一下接口的 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. HTML——<meta http-equiv="content-type" content="text/html; charset=UTF-8">

    没有添加这句话的编码方式的话,很容易就乱码了 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&g ...

  2. WCF编程系列(四)配置文件

    WCF编程系列(四)配置文件   .NET应用程序的配置文件 前述示例中Host项目中的App.config以及Client项目中的App.config称为应用程序配置文件,通过该文件配置可控制程序的 ...

  3. jfinal取消默认跳转到view.jsp页面的方法

    今天为了在一个列表中添加一个删除的方法,直接在方法里面谢了一个dao.del();方法,但是调用的时候却出现404错误. 然后就写了一句下面的代码 redirect("/api/listMe ...

  4. C# ACM poj1005

    大水题呀 public static void acm1005(int n, float[,] a) { float pi = 3.1415926f, rr; int years; ; i < ...

  5. (转)传统MySQL+ Memcached架构遇到的问题

    实际MySQL是适合进行海量数据存储的,通过Memcached将热点数据加载到cache,加速访问,很多公司都曾经使用过这样的架构,但随着业务数据量的不断增加,和访问量的持续增长,我们遇到了很多问题: ...

  6. 14_Request对象

    [HttpServletRequest简介] HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,开发人员通过 ...

  7. 计算 unique word numbers

    计算不重复单词的个数 参考: 1.Unique words count

  8. LNK1123: 转换到 COFF 期间失败: 文件无效或损坏[汇总]

    目前有两种方式可用于解决: 1. 微软官方的一个解决方案: http://support.microsoft.com/kb/320216/zh-cn 发现是嵌入清单的问题,于是对该工程以及所有依赖工程 ...

  9. Unity3D--学习太空射击游戏制作(二)

    步骤三:创建主角 游戏的主角是一艘太空飞船,我们将使用一个飞船模型作为游戏的主角,并赋予他一个脚本,控制他的运动,游戏体的组件必须依赖于脚本才能运行. 01:在Project窗口找到Player.fb ...

  10. 自定义弹出div对话框

    <style type="text/css"> html,body{height:100%;overflow:hidden;} body,div,h2{margin:0 ...