【问题标题】:What is the correct way to process REST requests in Contoller在Controller中处理REST请求的正确方法是什么
【发布时间】:2014-01-22 05:15:23
【问题描述】:

我为“应用程序”表创建了一个控制器。 Web 和 REST 界面可以正常工作,但我认为添加和编辑功能应该更好。

当我测试添加和编辑时,我发现需要以 web FORM 格式(而不是 JSON)发布数据。

我发现我需要在保存中使用“$this->request->input('json_decode')”来解码 JSON 数据。我以为这是自动发生的。

此函数现在适用于添加(编辑类似)并显示我的 json/add.ctp 以便我可以将成功记录返回给用户。

public function add() {
    if ($this->request->is('post')) {
        $this->Application->create();

        //Is the request REST passing a JSON object?
        if (preg_match('/\.json/', $this->request->here)){
            //This is a REST call
            $this->set('status', $this->Application->save($this->request->input('json_decode')));
        } else {
            //This is an interactive session
            if ($this->Application->save($this->request->data)) {
                $this->Session->setFlash(__('The application has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The application could not be saved. Please, try again.'));
            }
        }
    }
}

我使用“$this->request->here”来查看它是否以“.json”结尾。这是处理 REST 调用的“正确”方式吗?

【问题讨论】:

    标签: rest cakephp cakephp-2.4


    【解决方案1】:

    CakePHP Book 中有一个完整的部分用于说明这一点。我想它会回答你的问题:

    http://book.cakephp.org/2.0/en/development/rest.html

    【讨论】:

    • 我已经阅读并实现了它,但它似乎没有解码 JSON 发布数据。我必须确定它是一个 JSON 请求并解码数据。也许我错过了什么。
    • 我需要添加“$this->RequestHandler->addInputType('json', array('json_decode', true));”到我的功能,然后神奇的事情发生了。它在 RequestHandler 文档中。
    【解决方案2】:

    问题是,您的操作是否接受 JSON 数据和表单数据?还是只是 JSON 数据?

    .json 纯粹用于数据的输出,您可以发送带有 .xml 扩展名的 JSON 数据,不同之处在于一旦数据被消毒,它将以 XML 格式输出。

    if($this->request->is('post')) {
            if(empty($this->request->data)){
                $data = $this->request->input('json_decode', TRUE);
            } else {
                $data = $this->request->data;
            }
    } else {
            $data = $this->params['url'];
    }
    

    以上是你应该做的,检查数据是否来自表单,如果不是,解码 JSON,如果不是 POST,保存已包含在 URL 中的参数。

    我并不是说上述方法是“正确”的方法,但这可能就是您正在寻找的。

    【讨论】:

    • 是的,我认为这是一种更好的方法。我会试一试的。
    • 我认为这是我缺少的代码。我添加了“$this->RequestHandler->addInputType('json', array('json_decode', true));”到我的函数,然后 JSON 数据在 $this->request->data 中解码,这就是它在 doco 中所说的。
    猜你喜欢
    • 2014-09-23
    • 2019-12-28
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多