Here you can find first example of backbone.js and php.
In this Example 2, we will improve Example 1 by:
- Use collection of backbone.js ( collection is ordered sets of models)
- Using mysql, PDO we will retrieve message list
Demo
Download Source
So first of all create a new directory “example_2” in our project directory “php-backbone”, create a new html file “index.html” in this new “example_2” directory. and write following boilerplate html code in this new “index.html” file.
<!DOCTYPE html>
<html>
<head>
<title>php backbone.js example 2</title>
</head>
<body>
<!-- JavaScript -->
<script src="../js/jquery-2.0.3.min.js"></script>
<script src="../js/underscore-min.js"></script>
<script src="../js/backbone-min.js"></script>
<script src="../js/example_2.js"></script>
</body>
</html>
We have already included “example_2.js” in our “example_2/index.html”, now we need to create this js file in “js” directory. So create “example_2.js” file in js directory.
Now add “MessageModel” model in this file like below
var MessageModel = Backbone.Model.extend({
defaults: {
code: 0,
message: "Test Message"
}
});
add “MessageRouter” router and create an object of this router and start history like below
var MessageRouter = Backbone.Router.extend({
routes: {
"": "displayMessages"
},
displayMessages: function() {
}
});
var messageRouter = new MessageRouter();
Backbone.history.start();
now we have to check that our model and router are working well or not, in “displayMessages” function create object of model and log its message value.
displayMessages: function() {
var msg = new MessageModel();
console.log(msg.toJSON());
}
It should display output “Test Message” browser console.
Now we will add backbone.js collection, it is just an ordered sets of models. so write code in “example_2.js” like below.
var MessageCollection = Backbone.Collection.extend({
model: MessageModel
});
To test this “MessageCollection”, we will create some object of “MessageModel” and pass the list of model to collection and use a underscore.js iterator “each” function to retrieve data of “MessageCollection”.
So modify the “displayMessages” function like below.
displayMessages: function() {
var msg1 = new MessageModel({ code: "001", message: "Registration Successfully " });
var msg2 = new MessageModel({ code: "002", message: "Registration Failed" });
var msg3 = new MessageModel({ code: "003", message: "Login Successfully" });
var msg4 = new MessageModel({ code: "003", message: "Login Failed" });
var messageCollection = new MessageCollection([ msg1, msg2, msg3, msg4]);
_.each(messageCollection.models, function (msg) {
console.log( "code => "+ msg.get("code") +", message => "+ msg.get("message"));
});
}
Output in the console will like below.
code => 001, message => Registration Successfully
code => 002, message => Registration Failed
code => 003, message => Login Successfully
code => 003, message => Login Failed
Now we will work for view. so at first in “/example_2/index.html” we will add a div for contain message list and add a template for render each message item.
so add below code in index.html.
<div id="messageList"></div>
<!-- Templates -->
<script type="text/template" id="tpl-message-item">
<a href="#" id="<%= code %>"><%= message %></a>
</script>
In “js/example_2.js” file we will create two views, one for message list and another for message item. So add below two views in this file.
var MessageListView = Backbone.View.extend({
tagName: "ul",
render: function(eventName) {
_.each(this.model.models, function (msg) {
$(this.el).append(new MessageListItemView({model:msg}).render().el);
}, this);
return this;
}
});
var MessageListItemView = Backbone.View.extend({
tagName:"li",
template:_.template($('#tpl-message-item').html()),
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
And change the function “displayMessages” like below.
displayMessages: function() {
var msg1 = new MessageModel({ code: "001", message: "Registration Successfully " });
var msg2 = new MessageModel({ code: "002", message: "Registration Failed" });
var msg3 = new MessageModel({ code: "003", message: "Login Successfully" });
var msg4 = new MessageModel({ code: "003", message: "Login Failed" });
var messageCollection = new MessageCollection([msg1, msg2, msg3, msg4]);
var messageListView = new MessageListView({model:messageCollection});
$('#messageList').html(messageListView.render().el);
}
From browser access “example_2”, then you will get output in our browser like below.

PHP Backbone Output
Now we have to a simple thing that retrieve message list from mysql database by php and display it, our model, controller, view and router all are all most ready. so in our mysql database create a new table and insert new data using below script.
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` int(11) NOT NULL,
`message` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8;
INSERT INTO `messages` (`id`, `code`, `message`) VALUES
(1, 100, 'Continue'),
(2, 101, 'Switching Protocols'),
(3, 102, 'Processing'),
(4, 200, 'OK'),
(5, 201, 'Created'),
(6, 203, 'Non-Authoritative Information'),
(7, 204, 'No Content');
You will also find this sql script with source “db/messages.sql”.
Then create a new php file “example_2.php” in api and write code like below.
getMessages();
function getMessages() {
$sql = "select * FROM messages ORDER BY code";
try {
$db = getConnection();
$stmt = $db->query($sql);
$messages = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($messages);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection() {
$dbhost="localhost"; // Your Host Name, For Me It localhost
$dbuser="root"; // User Name, For Me It root
$dbpass="root"; // Password, For Me It root
$dbname="test"; // Database Name, For Me It test
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
Change $dbhost, $dbuser, $dbpass, $dbname as yours.
In above “getConnection()” function, its simple, we just connect to the database and return the handler using PDO.
In “getMessages” function we just retrieve messages as object and return the json result set.
In example_2.js we have to add the url to the Collection class “MessageCollection ” like below.
var MessageCollection = Backbone.Collection.extend({
model: MessageModel,
url: "../api/example_2.php"
});
Now we have to fetch messages, So change the “displayMessages” function like below.
displayMessages: function() {
var messageCollection = new MessageCollection();
var messageListView = new MessageListView({model:messageCollection});
messageCollection.fetch({
success: function () {
$('#messageList').html(messageListView.render().el);
}
});
}
So if you access this example “example_2” then we will get output like below.

PHP Backbone Output
If you have any question, feel free to ask in comment.
Demo
Download Source
23.764730
90.358066