2014-01-22 53 views
0

我爲「應用程序」表創建了一個控制器。 Web和REST界面正在工作,但我認爲添加和編輯功能應該更好。在Contoller中處理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呼叫的「正確」方式嗎?

回答

1

CakePHP Book中有整個部分。我認爲這會回答你的問題(S):

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

+0

我已閱讀並實施它,但它似乎沒有解碼JSON發佈數據。我必須確定它是一個JSON請求並解碼數據。也許我錯過了什麼。 – DuaneW

+0

我需要添加「$ this-> RequestHandler-> addInputType('json',array('json_decode',true));」對我的功能,然後魔術發生。它在RequestHandler doco中。 – DuaneW

0

的問題是,是否你的行動接受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參數。

我不是說上述是「正確」的方式來做到這一點,但這可能是你在找什麼。

+0

是的,我認爲這是一個更好的方式來做到這一點。我會試一試。 – DuaneW

+0

我認爲這是我錯過的代碼。我添加了「$ this-> RequestHandler-> addInputType('json',array('json_decode',true));」到我的函數,然後JSON數據在$ this-> request-> data中解碼,這就是它在doco中所說的內容。 – DuaneW

相關問題