cakephp json webservice for beginners

2019-04-17 02:33发布

I am beginner in cakephp
my task is to create restfull json web services
I have started from posts table
give my link to basic json webservice I have googled but some are for previous versions some are for xml I am not getting started I have cakephp 2.4 version

currently my controller is

<?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'));
    }

 }

View is

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

1- it is showing within default html template, I need pure json 2- it show each record as in Post array, don't need subarray that's it show like this

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

while I need

{"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}]} 

2条回答
放我归山
2楼-- · 2019-04-17 02:44

The official documentation describes how to create a RESTful site and it has a section about XML and json views as well.

Try the documentation, there are plenty of code examples as well.

查看更多
萌系小妹纸
3楼-- · 2019-04-17 02:53

Check out the friendsofcake/crud plugin. It has an Api Transform listener to generate the json format you need.

查看更多
登录 后发表回答