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认证
随机推荐
- 使用netbeans 搭建 JSF+SPRING 框架
spring版本使用4,jsf版本2.2 jsf的配置文件faces-config.xml <?xml version='1.0' encoding='UTF-8'?> <faces ...
- ASP.NET Web Service如何工作(1)
ASP.NET Web Service如何工作(1) [日期:2003-06-26] 来源:CSDN 作者:sunnyzhao(翻译) [字体:大 中 小] Summary ASP.NET Web ...
- Objective-C 学习笔记(Day 3,上)
------------------------------------------- 类方法 ①类方法: + 开头的方法(定义的过程形式和对象方法一样,只不过 + 开头,这是唯一的 ...
- Mysql的权限管理
权限管理 创建用户 语法: create user '用户名'[@'主机名'][identified by '密码']; 示例: 说明: 用户名必须使用引号 '主机名'可以是以 ...
- Tian Ji -- The Horse Racing
Tian Ji -- The Horse Racing Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Jav ...
- Demo02_对结构体进行文件读写_张仕传_作业_
#include <iostream> using namespace std; #define StructArrarySize 5 // 老师数量 #define StudentNum ...
- POJ 1170 Shopping Offers -- 动态规划(虐心的六重循环啊!!!)
题目地址:http://poj.org/problem?id=1170 Description In a shop each kind of product has a price. For exam ...
- NHibernate多对多关联映射的实现
上次用EF演示了数据库多对多关系的操作,这次我们还是引用上次的案例,来演示如何在C#当中使用NHibernate. 首先介绍一下NHibernate框架的来源.熟悉Java编程的读者肯定知道Hiber ...
- The preview is empty because of the setting.Check the generation option.
前些日子在pd中添加存储过程, 参考:深蓝居的博文 http://www.cnblogs.com/studyzy/archive/2009/12/18/1627334.html 创建视图的时候,会在属 ...
- Python设计模式——装饰模式(Decorator)
假如我们需要开发一个程序来展示一个人穿衣服的过程. #encoding=utf-8 __author__ = 'kevinlu1010@qq.com' class Person(): def __in ...