I have a Backbone application where use Codeigniter as backend. Now, to display data from my Database i use the RESTful API to get the data and pass it as JSON to Backbone. The data I want to fetch are Bandnames from A-Z and its always the same data: band_id and band_name. So for that purpose I want to create one single Backbone Model which should tell the Collections what data to handle. So in my Codeigniter setup, in the application
-folder->controllers
-folder I created an api
-folder, where I created an artist.php
-file, which basically looks like this:
<?php
require(APPPATH.'libraries/REST_Controller.php');
class artists extends REST_Controller{
// BANDS WITH LETTER A
public function a_get()
{
$this->load->database();
$sql = "SELECT band_id, band_name FROM `bands` WHERE bands_name LIKE 'A%' LIMIT 100";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artists with letter a!'), 404);
}
}
public function a_put()
{
// Update
}
public function a_post()
{
// Post/insert
}
public function a_delete()
{
// delete
}
// BANDS WITH LETTER B
public function b_get()
{
$this->load->database();
$sql = "SELECT band_id, band_name FROM `bands` WHERE band_name LIKE 'B%' LIMIT 10";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artists with letter b!'), 404);
}
}
public function b_put()
{
// Update
}
public function b_post()
{
// Post/insert
}
public function b_delete()
{
// delete
}
... LETTER C code
... LETTED D code etc. etc.
?>
My Backbone Model would look like this:
function($, Backbone) {
var BandModel = Backbone.Model.extend({
url: "../myproejct/index.php/api/bands/",
defaults: {
"band_id": ' ',
"band_name": ' '
}
});
return BandModel;
});
And a collection would look like this:
function(Backbone, BandModel) {
var BandCollectionA = Backbone.Collection.extend({
model: BandModel,
url: "../myproject/index.php/api/bands/a"
});
return BandCollectionA;
});
So my question is: can I do it like this? Can I do the API, the artists.php
, like that? Are there alternatives?