Another option you may consider is to roll with a pre-packaged RESTful framework that has all the necessary functions built in to execute your Backbone server queries. My personal favorite is Josh Lockhart's SlimPHP Framework.
Some simple sample code (once you have SlimPHP setup) used to take your Backbone calls look like this.
$app->get('/user', function() use ($app) {
// See if session is set, get user info as array
if (isset($_SESSION['userID']) {
$user = // grab user with userID data from DB
}
// Respond to the get request with a json object
$response = $app->response;
$response['Content-Type'] = 'application/json';
$response->body(json_encode($user));
}
Here is a POST example that turns Backbone json into arrays.
// Middleware that detects type of data and converts it to something usable
$app->add('Slim_Middleware_ContentTypes'); // JSON to associative array
...
$app->post('/message', function() use ($app) {
$dataIn = $app->request()->getBody();
...
// Save to DB $dataIn['message'], $dataIn['author'], etc.
}
Here is a PUT example using some parameters.
$app->put('/user/:id', function($id) use ($app) {
// Find appropriate user from DB that has $id as ID
$dataIn = $app->request()->getBody();
// Save to DB $dataIn['name'], $dataIn['age'], etc.
}
And here is a DELETE.
$app->delete('/message/:id', function($id) use ($app) {
// Find appropriate message from DB that has $id as ID
// Delete message with id of $id
}
While this isn't an exhaustive example of all the other things to consider, it should give you an idea of the kinds of open solutions already out there for you to use. I personally like Slim because it is so lightweight, simple, yet it has all the features you'd want in a RESTful server. Great for prototyping. Combine it with a DB abstraction layer and some other tools and you can make just about anything you want quicker.
You can see some other sample code along these lines here:
- How to post Backbone model to server
- Ways to save Backbone data
And here is a link to some other PHP based RESTful solutions: Framework List
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…