A Restful Persistence Solution Usable with Backbone.Js... in PHP

A RESTful persistence solution usable with backbone.js... in PHP?

EDIT Nov 2018: Although I wouldn't knock CodeIgniter, nowadays Laravel (currently 5.5) is the framework I use.

Here is a good article that sums up the reasons I use Laravel.

To get jump started, I recommend Laracasts. It's a subscription video tutorial service that goes in depth on how to use Laravel (and other web dev related things).

ORIGINAL ANSWER:

Codeigniter, to me, is the easiest of the Rails-like frameworks. It's bare bones, and you can build a CRUD app from scratch easily.

The biggest issue with rolling your own app is security. Codeigniter can help you build a less hackable site by shielding you from many of the common security risks, such as using $_POST arrays directly, and not properly filtering your data. Not to mention the many helper classes it offers such as form validation.

You can view the documentation on their website. It's very easy to use as long as you remember the navigation is hidden at the top of each page. :D

simple PHP code sample to serve backbone.js

The most basic and simple approach (I know of) that should help you to get started, would be:

  1. Given you have a model / collection, define it with an url like:

    resourceCollection: Backbone.Collection.extend({
    url: '/page.php'
    })

  2. Create your page.php file (in the document root), just take care of RewriteRules etc. you may use!

  3. 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']){
    ...
    }


Sync backbone.js to php/MySQL

The first thing that I would like to seriously emphasize that Backbone.js is definitely not hardwired to any specific server side architecture viz rails.
Many (most?) of the Backbone.js enthusiasts are also rails enthusiasts as Backbone.js is designed in harmony with restful patterns which rails community is very passionate about.

But if you dont want to use Rails, you can still take absolutely the FULL advantage of Backbone.js

First and foremost, decide if you want to implement a restful interface. Doing so is very easy in php. If you are using zend framework then you have the excellent Zend_Rest component to assist you in creating a powerful restful api. Alternatively you might want to look into comparitively new frameworks like Recess and Fuel that have built in support for creating restful apis conveniently with ease.

You can ofcourse code your own restful api through vanilla php.

Please note that following a few conventions will make Backbone integration very convenient.
Eg. backbone expects records to have an id field, also backbone expects that upon submission of a record server will return a json serialized updated record with updated fields, which will be used to update the client side model. Taking care of some such small things will enable you to create your application without overriding much of backbone's classes.

Now, if your rest api interface differs radically from the rails implementation or you are not implementing a rest api at all you will have to reprogram the Backbone.Model.sync function to suit your requirements.

Backbone.js How to use with PHP

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:

  1. How to post Backbone model to server
  2. Ways to save Backbone data

And here is a link to some other PHP based RESTful solutions: Framework List

how to develope CRUD by backbone.js by database

If I understand your question correctly it's something I was wondering about, I recently posted a question about RESTful persistence in PHP.

Since Javascript doesn't have access to the filesystem you can't use it to write to a database. You'll have to pick a backend server in another language like PHP, Rails, Ruby, whatever. There are a few suggestions for PHP at the link above.

Convert MySQL record set to JSON string in PHP

This should work:

function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you don´t really need to do anything here.
}
return json_encode($rs);
}

If you need to manipulate the result set you can use the following -more complex- version that lets you add a callback function that will be called on every record and must return that record already processed:

function recordSetToJson($mysql_result, $processing_function = null) {
$rs = array();
while($record = mysql_fetch_assoc($mysql_result)) {
if(is_callable($processing_function)){
// callback function received. Pass the record through it.
$processed = $processing_function($record);
// if null was returned, skip that record from the json.
if(!is_null($processed)) $rs[] = $processed;
} else {
// no callback function, use the record as is.
$rs[] = $record;
}
}
return json_encode($rs);
}

use it like this:

$json = recordSetToJson($results, 
function($record){
// some change you want to make to every record:
$record["username"] = strtoupper($record["username"]);
return $record;
});

How to use a php restful api-centric design internal instead of with http request

So you wan to have a code separation between your API and front-end stuff ? You could use Slim Framework to do that so you will have an easy maintainable code. Slim Framework is very easy to write models and also prepare the data for future use and even cache it.

Also have a look at this list of PHP RESTful API Frameworks:
http://davss.com/tech/php-rest-api-frameworks/

You could also take a different approach and use front-end models to do both the code separation and have a nice code structure. For that I recommend Backbone.js which will provide some nice key-value bindings and event handling for your front-end code.



Related Topics



Leave a reply



Submit