简体   繁体   English

CakePHP - 为我的cakephp应用程序创建API

[英]CakePHP - creating an API for my cakephp app

I have created a fully functional CakePHP web application. 我创建了一个功能齐全的CakePHP Web应用程序。 Now, i wanna get it to the next level and make my app more "opened". 现在,我想把它提升到一个新的水平,让我的应用程序更“开放”。 Thus i want to create an RESTful API. 因此,我想创建一个RESTful API。 In the CakePHP docs,i found this link ( http://book.cakephp.org/2.0/en/development/rest.html ) which describes the way to make your app RESTful. 在CakePHP文档中,我找到了这个链接( http://book.cakephp.org/2.0/en/development/rest.html ),它描述了使您的应用程序RESTful的方法。 I added in the routes.php the the two lines needed,as noted at the top of the link,and now i want to test it. 我在routes.php中添加了所需的两行,如链接顶部所示,现在我想测试它。 I have an UsersController.php controller,where there is a function add(),which adds new users to databases. 我有一个UsersController.php控制器,其中有一个函数add(),它将新用户添加到数据库。 But when i try to browse under mydomain.com/users.json (even with HTTP POST),this returns me the webpage,and not a json formatted page,as i was expecting . 但是,当我尝试在mydomain.com/users.json下浏览时(即使使用HTTP POST),这会返回我的网页,而不是像我期望的那样返回json格式的页面。

Now i think that i have done something wrong or i have not understood something correctly. 现在我认为我做错了什么或者我没有正确理解。 What's actually happening,can you help me a bit around here? 实际发生了什么,你能帮我一点吗?

Thank you in advace! 谢谢你的推荐!

You need to parse JSON extensions. 您需要解析JSON扩展。 So in your routes.php file add: 所以在你的routes.php文件中添加:

Router::parseExtensions('json');

So a URL like http://example.com/news/index you can now access like http://example.com/news/index.json . 因此,像http://example.com/news/index这样的网址现在可以访问http://example.com/news/index.json

To actually return JSON though, you need to amend your controller methods. 要实际返回JSON,您需要修改控制器方法。 You need to set a _serialize key in your action, so your news controller could look like this: 您需要在操作中设置_serialize键,因此您的新闻控制器可能如下所示:

<?php
class NewsController extends AppController {

    public function index() {
        $news = $this->paginate('News');
        $this->set('news', $news);
        $this->set('_serialize', array('news'));
    }
}

That's the basics. 这是基础知识。 For POST requests, you'll want to use the RequestHandler component. 对于POST请求,您将需要使用RequestHandler组件。 Add it to your controller: 将其添加到您的控制器:

<?php
class NewsController extends AppController {

    public $components = array(
        'RequestHandler',
        ...
    );

And then you can check if an incoming request used the .json file extension: 然后你可以检查传入的请求是否使用.json文件扩展名:

public function add() {
    if ($this->RequestHandler->extension == 'json') {
        // JSON request
    } else {
        // do things as normal
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM