【问题标题】:cakephp json webservice for beginners初学者的 cakephp json 网络服务
【发布时间】:2014-02-12 12:45:47
【问题描述】:

我是 cakephp 的初学者
我的任务是创建 restfull json web 服务
我从帖子表开始
给我的基本 json webservice 的链接 我已经用谷歌搜索了,但有些是以前的版本 有些是用于 xml 我还没开始 我有 cakephp 2.4 版本

目前 我的控制器是

<?php
class PostsController extends AppController {
    public function index() {
        //$posts= $this->Post->find('all');
        $this->set('posts', $this->Post->find('all'));
        //$this->set($posts);
    }
    public function view($id = null)
    {
        if(!$id)
        {
            throw new NotFoundException(__('View Not Found'));
        }
        $posts = $this->Post->findById($id);
        if(!$posts)
        {
            throw new NotFoundException(__('View Not Found'));
        }
        $this->set(compact('posts', 'posts'));
    }

 }

查看是

<?php
    echo json_encode(compact('posts', 'posts'));
?>

1- 它显示在默认的 html 模板中,我需要纯 json 2-它将每条记录显示为 Post 数组,不需要子数组 就是这样显示的

{"posts":{"Post":{"id":"1","title":"The title","body":"This is the post body.","created":"2014-02-08 00:35:50","modified":null}}} 

当我需要的时候

{"posts":[{"id":"1","title":"The title","body":"This is the post body.","created":"2014-02-08 00:35:50","modified":null}},{"id":"2","title":"A title once again","body":"And the post body follows.","created":"2014-02-08 00:35:50","modified":null}]} 

【问题讨论】:

  • 除非您提供一些代码证明您花时间在上面,否则我们无法帮助您。

标签: json web-services rest cakephp


【解决方案1】:

官方文档描述了如何创建一个 RESTful 站点,它也有一个关于 XML 和 json 视图的部分。

试试文档吧,里面也有很多代码示例。

【讨论】:

    【解决方案2】:

    查看friendsofcake/crud 插件。它有一个Api Transform listener 来生成你需要的json格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多