Experience level: newbie.
The backbone.js Todos demo uses localStorage. This question is about how to use PHP to serve the page instead, assuming that a MySQL DB has been set up.
I checked out PHP frameworks such as CodeIgniter but found them difficult to follow and possibly overkill for my learning purposes.
I understand the concept that a REST API needs to be set up. I am really looking for simple code samples. Thanks in advance.
Update: Is there a full backbone.js tutorial somewhere that includes a full working example of how to wire up to server side PHP?
The most basic and simple approach (I know of) that should help you to get started, would be:
Given you have a model / collection, define it with an url like:
resourceCollection: Backbone.Collection.extend({ url: '/page.php' })
Create your page.php file (in the document root), just take care of RewriteRules etc. you may use!
Now we have to make sure that we can react properly on get, put, post and delete; so we have to check for the request method, e.g. with a switch statement. Cases would be GET, DELETE, PUT, POST:
switch($_SERVER['REQUEST_METHOD']){ ... }
The following should give you an idea (php controllers are implemented using Silex framework + Paris library for the data access):
// GET /{resource}/{id} Show
$app->get('/api/todos/{id}', function ($id) use ($app) {
$todo = $app['paris']->getModel('Todo')->find_one($id);
return new Response(json_encode($todo->as_array()), 200, array('Content-Type' => 'application/json'));
});
// POST /{resource} Create
$app->post('/api/todos', function (Request $request) use ($app) {
$data = json_decode($request->getContent());
$todo = $app['paris']->getModel('Todo')->create();
$todo->title = $data->title;
$todo->save();
return new Response(json_encode($todo->as_array()), 200, array('Content-Type' => 'application/json'));
});
// PUT /{resource}/{id} Update
$app->put('/api/todos/{id}', function ($id, Request $request) use ($app) {
$data = json_decode($request->getContent());
$todo = $app['paris']->getModel('Todo')->find_one($id);
$todo->title = $data->title;
$todo->save();
return new Response('Todo updated', 200);
});
// DELETE /{resource}/{id} Destroy
$app->delete('/api/todos/{id}', function ($id) use ($app) {
$todo = $app['paris']->getModel('Todo')->find_one($id);
$todo->delete();
return new Response('Todo deleted', 200);
});
To get your backbone collection working with the above interface, all you have to do is to set the url property like:
window.TodoList = Backbone.Collection.extend({
model: Todo,
url: "api/todos",
...
});
Recently, I have written a tutorial on how to do GET/POST/PUT/DELETE with Backbone.js and PHP http://cambridgesoftware.co.uk/blog/item/59-backbonejs-%20-php-with-silex-microframework-%20-mysql, might be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With