2012-07-30 76 views
1

嗨,我是新来的CI和MVC一般,我想做一个REStful应用程序。CodeIgniter REST风格和控制器

我已经读了很多(真的),我有以下规格

的RESTful

读取(GET)

/object 
/object.xml 
/object.json 

读取ID(GET)

/object/id 
/object/id.xml 
/object/id.json 

创建(POST)

/object 
/object.xml 
/object.json 

更新(PUT)

/object/id 
/object/id.xml 
/object/id.json 

删除(DELETE)

/object/id 
/object/id.xml 
/object/id.json 

基于以上时扩展的.xml返回XML,当上传.json返回JSON和分机返回html

当谈到CI CRUD我有followig url

/object 
/object/edit/id 
/odject/delete/id 

我的问题是

我需要为REST风格的2个控制器1和1 CI CRUD或我只能有1个, ,我怎么可以有多个respesentation(HTML,XML,JSON)。

appricated(链接阅读时间)

感谢

回答

3

任何帮助看一看:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

你也可以做到这一点不同的方式,但是我觉得上面的可能是最好的开始的地方。

更新

另一种方式,可以使用航线。

$routes['object\.(xml|http|json)'] = 'process_object/$1'; 
$routes['object/(:num)\.(xml|http|json)'] = 'process_object/$2/$1'; 
$routes['object/crud/\.(xml|http|json)'] = 'process_object/$1/null/true'; 
$routes['object/crud/(:num)\.(xml|http|json)'] = 'process_object/$2/$1/true'; 

那么你process_object行动:

function process_object($Format = 'xml', $ID = null, $CRUD = false) 
{ 
    $method = $this->_detect_method(); // see http://stackoverflow.com/questions/5540781/get-a-put-request-with-codeigniter 
    $view = null; 
    $data = array(); 
    switch($method) 
    { 
     case 'get' : 
     { 
      if($CRUD !== false) 
       $view = 'CRUD/Get'; 
      if($ID === null) 
      { 
       // get a list 
       $data['Objects'] = $this->my_model->Get(); 
      } 
      else 
      { 
       $data['Objects'] = $this->my_model->GetById($ID); 
      } 
     } 
     break; 
     case 'put' : 
     { 
      if($CRUD !== false) 
       $view = 'CRUD/Put'; 
      $this->my_model->Update($ID, $_POST); 
     } 
     break; 
     case 'post' : 
     { 
      if($CRUD !== false) 
       $view = 'CRUD/Post'; 
      $this->my_model->Insert($_POST); 
     } 
     break; 
     case 'delete' : 
     { 
      if($CRUD !== false) 
       $view = 'CRUD/Delete'; 
      $this->my_model->Delete($ID); 
     } 
     break; 
    } 
    if($view != null) 
    { 
     $this->load->view($view, $data); 
    } 
    else 
    { 
     switch(strtolower($Format)) 
     { 
      case 'xml' : 
      { 
       // create and output XML based on $data. 
       header('content-type: application/xml'); 
      } 
      break; 
      case 'json' : 
      { 
       // create and output JSON based on $data. 
       header('content-type: application/json'); 
       echo json_encode($data); 
      } 
      break; 
      case 'xml' : 
      { 
       // create and output HTML based on $data. 
       header('content-type: text/html'); 
      } 
      break; 
     } 
    } 
} 

注:我没有反正测试此代码,所以它需要的工作。

+0

谢谢我已经看过这个,但这个有一个restfull控制器扩展,而不是CI。所以它不清楚我是否必须有2个控制器,因为2个控制器是双重工作。谢谢无论如何 – ntan 2012-07-30 10:52:57

+0

你可能“可能”拥有一个控制器,但是这样做可能会使事情复杂化。我正在看的另一种方式是使用路线。看到我更新的答案。 – Gavin 2012-07-30 11:02:17

+0

你有一点我会检查出来 – ntan 2012-07-30 11:19:22