使用CakePHP快速建立Restful服务

RESTful是面向互联网(HTTP)的WEB服务架构。

使用CakePHP1.3,创建Restful服务非常简洁优雅。

下面以http(s)://yourhost.com/deals.format为例介绍创建过程。


1、映射HTTP请求

添加如下语句到routes.php中

    /* Restful, add http mapping */
    Router::mapResources('deals');

其中deals代表互联网资源,这句话会把GET, POST, PUT, DELETE 方法映射到资源的index, view(show), add(creation), edit(update), delete操做。

对于所有需要建立RESTful的资源,该方法可以反复调用。


2、解析请求格式后缀

    Router::parseExtensions('json', 'xml');   
CakePHP支持xml, json, rss格式的请求应答。上面的代码使CakePHP能解析出json或xml应答格式。


3、在Controller中包含相应的component和helper

    public $components = array(
        'RequestHandler', //这个不能缺少,否则不能把theme指向xml/json目录
    );

    public $helpers = array(
        'Xml',                  //for xml
        'Javascript',      //for json
    );


4、创建缺省布局

在你的theme(可在beforeFilter中设置$this->theme)下面的layouts中添加xml和json的缺省布局

xml/default.ctp

json/default.ctp

内容分别是


<?php

//xml

    header('Content-type: application/xml');
    echo $this->Xml->header();
    echo $content_for_layout;
?>


<?php

//json

    header("Pragma: no-cache");
    header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
    header('Content-Type: text/x-json');
    header("X-JSON: ".$content_for_layout);

    echo $content_for_layout;
?>


5、创建视图模板

在你的theme下面添加view templates

deals/xml/index.ctp

deals/json/index.ctp

内容分别是

<deals>
    <?php echo $xml->serialize($deals); ?>
</deals>


<?php echo $javascript->object($deals); ?>

其中第2个是服务器json应答的处理。这里不要奇怪,js和json本来就息息相关。


6、测试

现在访问你的RESTful服务器,输入http://yourhost.com/deals.xml(或json)

将得到一个xml或json内容的输出。如:

<?xml version="1.0" encoding="UTF-8" ?>
<deals>
	<deal id="416" slug="awardtest123" city_id="1011" region_id="" min_buyers="1" max_buyers="2" />
        <deal id="414" slug="hktest12345_02820870013164958611375" city_id="1030" region_id="" min_buyers="1" max_buyers="2" />
</deals>


by iefreer

midnight again...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值