1

嗨,我是 CI 和 MVC 的新手,我正在尝试制作一个 RESTful 应用程序。

我已经阅读了很多(真的)并且我有以下规范

RESTful

读取(获取)

/object
/object.xml 
/object.json 

读取 ID (GET)

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

创建(发布)

/object
/object.xml 
/object.json 

更新 (PUT)

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

删除(删除)

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

基于上述当扩展名是.xml时返回xml,当.json返回json并且扩展名返回html时

当谈到 CI CRUD 我有以下网址

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

我的问题是

我是否需要 2 个控制器 1 个用于 RESTful,1 个用于 CI CRUD,或者我只能有 1 个,我怎样才能拥有多个响应(html、xml、json)。

任何帮助(阅读链接)

谢谢

4

1 回答 1

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;
        }
    }
}

注意:无论如何我都没有测试过这个代码,所以它需要工作。

于 2012-07-30T10:50:11.847 回答