API-based Web Application with Backbone, Require.js and Slim framework

Posted by on Sep 21, 2013 in Front-end, PHP Programming | 2 Comments

A single-page application (SPA) was something I’ve been exploring for the last few months. I always liked the idea of moving certain responsibilities to the client’s side. After all, why would you like to waste server’s RAM/CPU to buil a HTML page (and pay for a transfer to deliver it) when a web browser is perfectly capable of doing that on its own? You will not only save money but also provide a better user experience. In addition to the performance, moving the presentation layer to the web browser gives a clearer division between back-end and front-end code.

Recently I came across an extremely useful boilerplate for Backbone.js created by Thomas Davis. The boilerplate brings together one of the most popular (and useful) front-end libraries:

It’s a great start because if you are new to those technologies it’s really hard to guess what would be the best way to put everything together. I used it as a foundation to create an example App which talks to a PHP back-end.

The back-end could be a plain PHP but instead I went for the Slim micro framework. It’s fast, very easy to learn and will enforce a better code structure. After all, this is one of the best use cases for a micro framework.

Before I will go into details get a copy of the example from GitHub and install it on your web server.

When you open the page in your web browser you should see something like this:

backbone-1

A very minimalistic website with 3 links in the main content area. You can add some more if you follow the “create” link in the gray nav bar.

While you’re switching between pages to submit a new URL, notice that your web browser won’t reload. All front-end code is stored in JavaScript. When the web browser needs to talk to the web server it does it in the background with AJAX. It makes the application very responsive and limits number of requests.

To understand how it works lets have a look into “public/index.php“. The script defines 3 endpoints:

  • $app->get(‘/link/latest‘, function () use ($app)
  • $app->post(‘/link/submit‘, function () use ($app)
  • $app->get(‘/‘, function() use ($app)

The first one returns a JSON object with all available links. In the real live it would look for them in a database but for the sake of simplicity I’m using a session. The second one handles POST request and stores links in the session. The last one is the simplest. It renders “templates/index.php” for all requests to the root “/”.

The template is an almost empty HTML5 file.

The only interesting line here is:

This is where the front-end gets initialised. It loads the Require.js library and refers it to js/main.js.

If you’re not familiar with Require.js it’s a module loader. Small but powerful library for breaking JavaScript code into multiple files/modules. If you want to learn only one new front-end framework this is where I would start. It has a good documentation and will help you organise your JavaScripts.

The next file we are going to look at is obviously “public/js/main.js”.

It loads 3 modules: views/app.js, router.js and vm.js.

Router.js is the heart of the application. It defines available pages and assigns them with the appropriate views.

The AppRouter extends Backbone.js router which is documented on the official website.

In this example we have only one custom route – “create“. It’s handled by “public/js/views/create.js“. Any other request will be resolved to the default action handled by “public/js/views/index.js“.

The index view does two things: initialise and render. When the object is initialised it’s calling LinksModel (public/js/models/links.js) model to fetch all links from the PHP back-end.

Once a JSON object is successfully pulled from the web server the “public/templates/index/index.html” template is parsed and rendered with Lo-Dash template function.

The LinksModel I mentioned above extends Backbone.js model. Backbone models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. It’s a very useful and important entity so try to learn more about it.

In our example the model defines a data type called “links” which is an array and a URL “link/latest” to populate the defaults from.

As you can see it’s all quite simple. The only problem is that you have to embrace multiple JavaScript frameworks at once but the boilerplate makes it much easier. What I really like about this setup is the structure. It’s similar to how things are done in the back-end and it should be fine even with big applications.

I know that some developers feel anxious about writing one application in two languages simultaneously. I can sympathise with them because I prefer simple solution. The problem is that we like it or not, the web applications will have more and more JavaScript code. As the old saying goes – “if you can’t fight them, join them”. With the latest front-end frameworks you can improve user experience, cut hosting costs and have a well structured code. Single-page applications will probably become the industry standard in the next few years so you have all the reasons to give it a go.

2 Comments

  1. Kirsten
    27/09/2013

    Nice work Lukasz, glad you’re making use of backbone, it’s a great JS framework (especially if you’re looking for good backwards compatibility in IE.

    Pretty much all our work makes extensive use of this methodology: we’ll write a REST api and have a single page JS application handle handle the front-end rendering whilst updating via asynchronous calls. Here’s a good example of how we hooked backbone.js into faceted search powered by Elastic Search (damn, can’t add links! try google for Havells Sylvannia website and use their product finder)

    We’re currently building a real-time trading app and are using Angular.js. I’d recommend you try it as we’ve had fantastic success, so much so that it’ll be our first port of call from now on (as opposed to backbone) unless we need to support archaic browsers!

    I hope you’re keeping well: didn’t get chance to say goodbye.

    Reply
  2. vLight
    15/01/2014

    Aren’t undesroce.js and lo-dash almost the same?
    If you prefer lo-dash’s templates, why not replace one with another (only if it possible of course)

    Reply

Leave a Reply