Reputation: 2205
Hi i am new to CI and MVC in general and i am trying to make a REStful application.
I have read a lot (really) and i have the following specification
RESTful
Read (GET)
/object
/object.xml
/object.json
Read id (GET)
/object/id
/object/id.xml
/object/id.json
Create (POST)
/object
/object.xml
/object.json
Update (PUT)
/object/id
/object/id.xml
/object/id.json
Delete (DELETE)
/object/id
/object/id.xml
/object/id.json
Based on the above when extension is .xml return xml, when .json returns json and on extension returns html
When comes to CI CRUD i have the followig urls
/object
/object/edit/id
/odject/delete/id
My question is
Do i need 2 controllers 1 for RESTful and 1 for CI CRUD or i can have only 1, and how can i have the multiple respesentation (html,xml,json).
Any help appricated (link for reading too)
Thanks
Upvotes: 1
Views: 4580
Reputation: 6394
Take a look at: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
You can also do this a different way, however I think the above is probably the best place to start.
Update
Another way, could be to use routes.
$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';
Then your process_object
action:
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;
}
}
}
Note: I haven't tested this code in anyway, so it will need work.
Upvotes: 3