Combining Laravel 4 and Backbone

For this tutorial, we're going to be building a single page app using Laravel 4 and Backbone.js. Both frameworks make it very easy to use a different templating engine other than their respective default, so we're going to use Mustache, which is an engine that is common to both. By using the same templating language on both sides of our application, we'll be able to share our views betweem them, saving us from having to repeat our work multiple times.

Our Backbone app will be powered by a Laravel 4 JSON API which we'll develop together. Laravel 4 comes with some new features that make the development of this API very easy. I'll show you a few tricks along the way to allow you to stay a bit more organized.

All of our dependencies will be managed by Package Managers, there will be no manual downloading or updating of libraries for this application! In addition, I'll be showing you how to leverage a little extra power from some of our dependencies.

For this project we'll be using:

To complete this tutorial, you'll need the following items installed:

  • Composer: You can download this from the homepage, I recommend the global install instructions located here.
  • Node + NPM: the installer on the homepage will install both items.
  • LESS Compiler: If you're on a Mac, I recommend CodeKit. However, regardless of your operating system, or if you do not feel like paying for CodeKit, you can just install the LESS Compiler for Node.js by typing npm install -g less at the command prompt.

Part 1: The Base Architecture

First things first, we need to get our application setup before we can begin adding our business logic to it. We'll do a basic setup of Laravel 4 and get all of our dependencies installed using our Package Managers.

Git

Let's start by creating a git repository to work in. For your reference, this entire repo will be made publicly available at https://github.com/conarwelsh/nettuts-laravel4-and-backbone.

Laravel 4 Installation

Laravel 4 uses Composer to install all of its dependencies, but first we'll need an application structure to install into. The "develop" branch on Laravel's Github repository is the home for this application structure. However, at the time of writing this article, Laravel 4 was still in beta, so I needed to be prepared for this structure to change at any time. By adding Laravel as a remote repository, we can pull in these changes whenever we need to. In fact, while something is in beta-mode, it's a good practice to run these commands after each composer update. However, Laravel 4 is now the newest, stable version.

So we have the application structure, but all of the library files that Laravel needs are not yet installed. You'll notice at the root of our application there's a file called composer.json. This is the file that will keep track of all the dependencies that our Laravel application requires. Before we tell Composer to download and install them, let's first add a few more dependencies that we're going to need. We'll be adding:

  • Jeffrey Way's Generators: Some very useful commands to greatly improve our workflow by automatically generating file stubs for us.
  • Laravel 4 Mustache: This will allow us to seamlessly use Mustache.php in our Laravel project, just as we would Blade.
  • Twitter Bootstrap: We'll use the LESS files from this project to speed up our front-end development.
  • PHPUnit: We'll be doing some TDD for our JSON API, PHPUnit will be our testing engine.
  • Mockery: Mockery will help us "mock" objects during our testing.

PHPUnit and Mockery are only required in our development environment, so we'll specify that in our composer.json file.


composer.json

Now we just need to tell Composer to do all of our leg work! Below, notice the --dev switch, we're telling composer that we're in our development environment and that it should also install all of our dependencies listed in "require-dev".

After that finishes installing, we'll need to inform Laravel of a few of our dependencies. Laravel uses "service providers" for this purpose. These service providers basically just tell Laravel how their code is going to interact with the application and to run any necessary setup procedures. Open up app/config/app.php and add the following two items to the "providers" array. Not all packages require this, only those that will enhance or change the functionality of Laravel.


app/config/app.php

Lastly, we just need to do some generic application tweaks to complete our Laravel installation. Let's open up bootstrap/start.php and tell Laravel our machine name so that it can determine what environment it's in.


bootstrap/start.php

Replace "your-machine-name" with whatever the hostname for your machine is. If you are unsure of what your exact machine name is, you can just type hostname at the command prompt (on Mac or Linux), whatever it prints out is the value that belongs in this setting.

We want our views to be able to be served to our client from a web request. Currently, our views are stored outside of our public folder, which would mean that they are not publicly accessible. Luckily, Laravel makes it very easy to move or add other view folders. Open up app/config/view.php and change the paths setting to point to our public folder. This setting works like the PHP native include path, it will check in each folder until it finds a matching view file, so feel free to add several here:


app/config/view.php

Next you will need to configure your database. Open up app/config/database.php and add in your database settings.

Note: It is recommended to use 127.0.0.1 instead of localhost. You get a bit of a performance boost on most systems, and with some system configurations, localhost will not even connect properly.

Finally, you just need to make sure that your storage folder is writable.

Laravel is now installed, with all of its dependencies, as well as our own dependencies. Now let's setup our Backbone installation!

Just like our composer.json installed all of our server-side dependencies, we'll create a package.json in our public folder to install all of our client-side dependencies.

For our client-side dependencies we'll use:

  • Underscore.js: This is a dependency of Backbone.js, and a handy toolbelt of functions.
  • Backbone.js: This is our client-side MVC that we'll use to build out our application.
  • Mustache.js: The Javascript version of our templating library, by using the same templating language both on the client and the server, we can share views, as opposed to duplicating logic.

public/package.json

Now just switch into your public folder, and run npm install. After that completes, lets switch back to our application root so we're prepared for the rest of our commands.

Package managers save us from a ton of work, should you want to update any of these libraries, all you have to do is run npm update or composer update. Also, should you want to lock any of these libraries in at a specific version, all you have to do is specify the version number, and the package manager will handle the rest.

To wrap up our setup process we'll just add in all of the basic project files and folders that we'll need, and then test it out to ensure it all works as expected.

We'll need to add the following folders:

  • public/views
  • public/views/layouts
  • public/js
  • public/css

And the following files:

  • public/css/styles.less
  • public/js/app.js
  • public/views/app.mustache

To accomplish this, we can use a one-liner:

Twitter Bootstrap also has two JavaScript dependencies that we'll need, so let's just copy them from the vendor folder into our public folder. They are:

  • html5shiv.js: allows us to use HTML5 elements without fear of older browsers not supporting them
  • bootstrap.min.js: the supporting JavaScript libraries for Twitter Bootstrap

For our layout file, the Twitter Bootstrap also provides us with some nice starter templates to work with, so let's copy one into our layouts folder for a head start:

Notice that I am using a blade extension here, this could just as easily be a mustache template, but I wanted to show you how easy it is to mix the templating engines. Since our layout will be rendered on page load, and will not need to be re-rendered by the client, we are safe to use PHP here exclusively. If for some reason you find yourself needing to render this file on the client-side, you would want to switch this file to use the Mustache templating engine instead.

Now that we have all of our basic files in place, let's add some starter content that we can use to test that everything is working as we would expect. I'm providing you with some basic stubs to get you started.


public/css/styles.less

We'll just import the Twitter Bootstrap files from the vendor directory as opposed to copying them. This allows us to update Twitter Bootstrap with nothing but a composer update.

We declare our variables at the end of the file, the LESS compiler will figure out the value of all of its variables before parsing the LESS into CSS. This means that by re-defining a Twitter Bootstrap variable at the end of the file, the value will actually change for all of the files included, allowing us to do simple overrides without modifying the Twitter Bootstrap core files.


public/js/app.js

Now we'll wrap all of our code in an immediately-invoking-anonymous-function that passes in a few global objects. We'll then alias these global objects to something more useful to us. Also, we'll cache a few jQuery objects inside the document ready function.


public/views/layouts/application.blade.php

Next is just a simple HTML layout file. We're however using the asset helper from Laravel to aid us in creating paths to our assets. It is good practice to use this type of helper, because if you ever happen to move your project into a sub-folder, all of your links will still work.

We made sure that we included all of our dependencies in this file, and also added the jQuery dependency. I chose to request jQuery from the Google CDN, because chances are the visiting user of this site will already have a copy from that CDN cached in their browser, saving us from having to complete the HTTP request for it.

One important thing to note here is the way in which we are nesting our view. Mustache does not have Block Sections like Blade does, so instead, the contents of the nested view will be made available under a variable with the name of the section. I will point this out when we render this view from our route.


public/views/app.mustache

Next is just a simple view that we'll nest into our layout.


app/routes.php

Laravel should have already provided you with a default route, all we're doing here is changing the name of the view which that route is going to render.

Remember from above, I told you that the nested view was going to be available under a variable named whatever the parent section was? Well, when you nest a view, the first parameter to the function is the section name:

In our nest command we called the section "content", that means if we echo $content from our layout, we'll get the rendered contents of that view. If we were to do return View::make('layouts.application')->nest('foobar', 'app'); then our nested view would be available under a variable named $foobar.

With all of our basic files in place, we can test to ensure everything went OK. Laravel 4 utilizes the new PHP web server to provide us with a great little development environment. So long to the days of having a million virtual hosts setup on your development machine for every project that you work on!

Note: make sure that you've compiled your LESS file first!

If you followed along correctly, you should be laughing hysterically at my horrible sense of humor, and all of our assets should be properly included into the page.


Part 2: Laravel 4 JSON API

Now we'll build the API that will power our Backbone application. Laravel 4 makes this process a breeze.

API Guidelines

First let's go over a few general guidelines to keep in mind while we build our API:

  • Status Codes: Responses should reply with proper status codes, fight the temptation to just place an { error: "this is an error message" } in the body of your response. Use the HTTP protocol to its fullest!

    • 200: success
    • 201: resource created
    • 204: success, but no content to return
    • 400: request not fulfilled //validation error
    • 401: not authenticated
    • 403: refusal to respond //wrong credentials, do not have permission (un-owned resource)
    • 404: not found
    • 500: other error
  • Resource Methods: Even though controllers will be serving different resources, they should still have very similar behavior. The more predictable your API is, the easier it is to implement and adopt.

    • index: Return a collection of resources.
    • show: Return a single resource.
    • create: Return a form. This form should detail out the required fields, validation, and labels as best as possible. As well as anything else needed to properly create a resource. Even though this is a JSON API, it is very useful to return a form here. Both a computer and a person can parse through this form, and very easily decipher which items are needed to fill out this form successsfully. This is a very easy way to "document" the needs of your API.
    • store: Store a new resource and return with the proper status code: 201.
    • edit: Return a form filled with the current state of a resource. This form should detail out the required fields, validation, and labels as best as possible. As well as anything else needed to properly edit a resource.
    • update: Update an existing resource and return with the proper status code.
    • delete: Delete an existing resource and return with the proper status code: 204.

Routing & Versioning

API's are designed to be around for a while. This is not like your website where you can just change its functionality at the drop of a dime. If you have programs that use your API, they are not going to be happy with you if you change things around and their program breaks. For this reason, it's important that you use versioning.

We can always create a "version two" with additional, or altered functionality, and allow our subscribing programs to opt-in to these changes, rather than be forced.

Laravel provides us with route groups that are perfect for this, place the following code ABOVE our first route:

Generating Resources

We're going to use Jeffrey Way's generators to generate our resources. When we generate a resource, it will create the following items for us:

  • Controller
  • Model
  • Views (index.blade.php, show.blade.php, create.blade.php, edit.blade.php)
  • Migration
  • Seeds

We're only going to need two resources for this app: a Post resource and a Comment resource.

Note: in a recent update to the generators, I have been receiving a permissions error due to the way my web servers are setup. To remedy this problem, you must allow write permissions to the folder that the generators write the temp file to.

Run the generate:resource command

You should now pause for a second to investigate all of the files that the generator created for us.

Adjust the Generated Resources

The generate:resource command saved us a lot of work, but due to our unique configuration, we're still going to need to make some modifications.

First of all, the generator placed the views it created in the app/views folder, so we need to move them to the public/views folder


app/routes.php

We decided that we wanted our API to be versioned, so we'll need to move the routes that the generator created for us into the version group. We'll also want to namespace our controllers with the corresponding version, so that we can have a different set of controllers for each version we build. Also the comments resource needs to be nested under the posts resource.

Since we namespaced our controllers, we should move them into their own folder for organization, let's create a folder named V1 and move our generated controllers into it. Also, since we nested our comments controller under the posts controller, let's change the name of that controller to reflect the relationship.

We'll need to update the controller files to reflect our changes as well. First of all, we need to namespace them, and since they are namespaced, any classes outside of that namespace will need to be manually imported with the use statement.

app/controllers/PostsController.php

app/controllers/PostsCommentsController.php

We also need to update our CommentsController with our new name: PostsCommentsController

Adding in Repositories

By default, repositories are not part of Laravel. Laravel is extremely flexible though, and makes it very easy to add them in. We're going to use repositories to help us separate our logic for code re-usability, as well as for testing. For now we'll just get setup to use repositories, we'll add in the proper logic later.

Let's make a folder to store our repositories in:

To let our auto-loader know about this new folder, we need to add it to our composer.json file. Take a look at the updated "autoload" section of our file, and you'll see that we added in the repositories folder.

composer.json

Seeding Our Database

Database seeds are a useful tool, they provide us with an easy way to fill our database with some content. The generators provided us with base files for seeding, we merely need to add in some actual seeds.

app/database/seeds/PostsTableSeeder.php

app/database/seeds/CommentsTableSeeder.php

Don't forget to run composer dump-autoload to let the Composer auto loader know about the new migration files!

Now we can run our migrations and seed the database. Laravel provides us with a single command to do both:

Tests

Testing is one of those topics in development that no one can argue the importance of, however most people tend to ignore it due to the learning curve. Testing is really not that difficult and it can dramatically improve your application. For this tutorial, we'll setup some basic tests to help us ensure that our API is functioning properly. We'll build this API TDD style. The rules of TDD state that we are not allowed to write any production code until we have failing tests that warrants it. However, if I were to walk you through each test individually, this would prove to be a very long tutorial, so in the interest of brevity, I will just provide you with some tests to work from, and then the correct code to make those tests pass afterwards.

Before we write any tests though, we should first check the current test status of our application. Since we installed PHPUnit via composer, we have the binaries available to us to use. All you need to do is run:

Whoops! We already have a failure! The test that is failing is actually an example test that comes pre-installed in our Laravel application structure, this tests against the default route that was also installed with the Laravel application structure. Since we modified this route, we cannot be surprised that the test failed. We can however, just delete this test altogether as it does not apply to our application.

If you run the PHPUnit command again, you will see that no tests were executed, and we have a clean slate for testing.

Note: it is possible that if you have an older version of Jeffrey Way's generators that you'll actually have a few tests in there that were created by those generators, and those tests are probably failing. Just delete or overwrite those tests with the ones found below to proceed.

For this tutorial we'll be testing our controllers and our repositories. Let's create a few folders to store these tests in:

Now for the test files. We're going to use Mockery to mock our repositories for our controller tests. Mockery objects do as their name implies, they "mock" objects and report back to us on how those objects were interacted with.

In the case of the controller tests, we do not actually want the repositories to be called, after all, these are the controller tests, not the repository tests. So Mockery will set us up objects to use instead of our repositories, and let us know whether or not those objects were called as we expected them to.

In order to pull this off, we'll have to tell the controllers to use our "mocked" objects as opposed to the real things. We'll just tell our Application to use a mocked instance next time a certain class is requested. The command looks like this:

The overall mocking process will go something like this:

  • Create a new Mockery object, providing it the name of the class which it is to mock.
  • Tell the Mockery object which methods it should expect to receive, how many times it should receive that method, and what that method should return.
  • Use the command shown above to tell our Application to use this new Mockery object instead of the default.
  • Run the controller method like usual.
  • Assert the response.

app/tests/controllers/CommentsControllerTest.php

app/tests/controllers/PostsControllerTest.php

Next, we'll follow the exact same procedure for the PostsController tests


app/tests/repositories/EloquentCommentRepositoryTest.php

Now for the repository tests. In writing our controller tests, we pretty much already decided what most of the interface should look like for the repositories. Our controllers needed the following methods:

  • findById($id)
  • findAll()
  • instance($data)
  • store($data)
  • update($id, $data)
  • destroy($id)

The only other method that we'll want to add here is a validate method. This will mainly be a private method for the repository to ensure that the data is safe to store or update.

For these tests, we're also going to add a setUp method, which will allow us to run some code on our class, prior to the execution of each test. Our setUp method will be a very simple one, we'll just make sure that any setUp methods defined in parent classes are also called using parent::setUp() and then simply add a class variable that stores an instance of our repository.

We'll use the power of Laravel's IoC container again to get an instance of our repository. The App::make() command will return an instance of the requested class, now it may seem strange that we do not just do $this->repo = new EloquentCommentRepository(), but hold that thought, we'll come back to it momentarily. You probably noticed that we're asking for a class called EloquentCommentRepository, but in our controller tests above, we were calling our repository CommentRepositoryInterface... put this thought on the back-burner as well... explainations for both are coming, I promise!

app/tests/repositories/EloquentPostRepositoryTest.php

Now that we have all of our tests in place, let's run PHPUnit again to watch them fail!

You should have a whole ton of failures, and in fact, the test suite probably did not even finish testing before it crashed. This is OK, that means we have followed the rules of TDD and wrote failing tests before production code. Although, typically these tests would be written one at a time and you would not move on to the next test until you had code that allowed the previous test to pass. Your terminal should probably look something like mine at the moment:

Screenshot

What's actually failing is the assertViewHas method in our controller tests. It's kind of intimidating to deal with this kind of an error when we have lumped together all of our tests without any production code at all. This is why you should always write the tests one at a time, as you'll find these errors in stride, as opposed to just a huge mess of errors at once. For now, just follow my lead into the implementation of our code.


Sidebar Discussion

Before we proceed with the implementations, let's break for a quick sidebar discussion on the responsibilities of the MVC pattern.

From The Gang of Four:

The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input.

The point of using a structure like this is to remain encapsulated and flexible, allowing us to exchange and reuse components. Let's go through each part of the MVC pattern and talk about its reusability and flexibility:

View

I think most people would agree that a View is supposed to be a simple visual representation of data and should not contain much logic. In our case, as developers for the web, our View tends to be HTML or XML.

  • reusable: always, almost anything can create a view
  • flexible: not having any real logic in these layers makes this very flexible

Controller

If a Controller "defines the way the user interface reacts to user input", then its responsibility should be to listen to user input (GET, POST, Headers, etc), and build out the current state of the application. In my opinion, a Controller should be very light and should not contain more code than is required to accomplish the above.

  • reusable: We have to remember that our Controllers return an opinionated View, so we cannot ever call that Controller method in a practical way to use any of the logic inside it. Therefore any logic placed in Controller methods, must be specific to that Controller method, if the logic is reusable, it should be placed elsewhere.
  • flexible: In most PHP MVCs, the Controller is tied directly to the route, which does not leave us very much flexibility. Laravel fixes this issue by allowing us to declare routes that use a controller, so we can now swap out our controllers with different implementations if need be:

Model

The Model is the "application object" in our definition from the Gang of Four. This is a very generic definition. In addition, we just decided to offload any logic that needs to be reusable from our Controller, and since the Model is the only component left in our defined structure, it's logical to assume that this is the new home for that logic. However, I think the Model should not contain any logic like this. In my opinion, we should think of our "application object", in this case as an object that represents its place in the data-layer, whether that be a table, row, or collection entirely depends on state. The model should contain not much more than getters and setters for data (including relationships).

  • reusable: If we follow the above practice and make our Models be an object that represents its place in the database, this object remains very reusable. Any part of our system can use this model and by doing so gain complete and unopinionated access to the database.
  • flexible: Following the above practice, our Model is basically an implementation of an ORM, this allows us to be flexible, because we now have the power to change ORM's whenever we'd like to just by adding a new Model. We should probably have a pre-defined interface that our Model's must abide by, such as: all, find, create, update, delete. Implementation of a new ORM would be as simple as ensuring that the previously mentioned interface was accomodated.

Repository

Just by carefully defining our MVC components, we orphaned all kinds of logic into no-man's land. This is where Repositories come in to fill the void. Repositories become the intermediary of the Controllers and Models. A typical request would be something like this:

  • The Controller receives all user input and passes it to the repository.
  • The Repository does any "pre-gathering" actions such as validation of data, authorization, authentication, etc. If these "pre-gathering" actions are successful, then the request is passed to the Model for processing.
  • The Model will process all of the data into the data-layer, and return the current state.
  • The Repository will handle any "post-gathering" routines and return the current state to the controller.
  • The Controller will then create the appropriate view using the information provided by the repository.

Our Repository ends up as flexible and organized as we have made our Controllers and Models, allowing us to reuse this in most parts of our system, as well as being able to swap it out for another implementation if needed.

We have already seen an example of swapping out a repository for another implementation in the Controller tests above. Instead of using our default Repository, we asked the IoC container to provide the controller with an instance of a Mockery object. We have this same power for all of our components.

What we have accomplised here by adding another layer to our MVC, is a very organized, scalable, and testable system. Let's start putting the pieces in place and getting our tests to pass.


Controller Implementation

If you take a read through the controller tests, you'll see that all we really care about is how the controller is interacting with the repository. So let's see how light and simple that makes our controllers.

Note: in TDD, the objective is to do no more work than is required to make your tests pass. So we want to do the absolute bare minimum here.

app/controllers/V1/PostsController.php

app/controllers/PostsCommentsController.php

It doesn't get much simpler than that, all the Controllers are doing is handing the input data to the repository, taking the response from that, and handing it to the View, the View in our case is merely JSON for most of our methods. When we return an Eloquent Collection, or Eloquent Model from a Controller in Laravel 4, the object is parsed into JSON auto-magically, which makes our job very easy.

Note: notice that we added a few more "use" statements to the top of the file to support the other classes that we're using. Do not forget this when you're working within a namespace.

The only thing that is a bit tricky in this controller is the constructor. Notice we're passing in a typed variable as a dependency for this Controller, yet there is no point that we have access to the instantiation of this controller to actually insert that class... welcome to dependency injection! What we're actually doing here is hinting to our controller that we have a dependency needed to run this class and what its class name is (or its IoC binding name). Laravel uses App::make() to create its Controllers before calling them. App::make() will try to resolve an item by looking for any bindings that we may have declared, and/or using the auto-loader to provide an instance. In addition, it will also resolve any dependencies needed to instantiate that class for us, by more-or-less recursively calling App::make() on each of the dependencies.

The observant, will notice that what we're trying to pass in as a dependency is an interface, and as you know, an interface cannot be instantiated. This is where it gets cool and we actually already did the same thing in our tests. In our tests however, we used App::instance() to provide an already created instance instead of the interface. For our Controllers, we're actually going to tell Laravel that whenever an instance of PostRepositoryInterface is requested, to actually return an instance of EloquentPostRepository.

Open up your app/routes.php file and add the following to the top of the file

After adding those lines, anytime App::make() asks for an instance of PostRepositoryInterface, it will create an instance of EloquentPostRepository, which is assumed to implement PostRepositoryInterface. If you were to ever change your repository to instead use a different ORM than Eloquent, or maybe a file-based driver, all you have to do is change these two lines and you're good to go, your Controllers will still work as normal. The Controllers actual dependency is any object that implements that interface and we can determine at run-time what that implementation actually is.

The PostRepositoryInterface and CommentRepositoryInterface must actually exist and the bindings must actually implement them. So let's create them now:

app/repositories/PostRepositoryInterface.php

app/repositories/CommentRepositoryInterface.php

Now that we have our two interfaces built, we must provide implementations of these interfaces. Let's build them now.

app/repositories/EloquentPostRepository.php

As the name of this implementation implies, we're relying on Eloquent, which we can call directly. If you had other dependencies, remember that App::make() is being used to resolve this repository, so you can feel free to use the same constructor method we used with our Controllers to inject your dependencies.

app/repositories/EloquentCommentRepository.php

If you take a look in our repositories, there are a few Exceptions that we are throwing, which are not native, nor do they belong to Laravel. Those are custom Exceptions that we're using to simplify our code. By using custom Exceptions, we're able to easily halt the progress of the application if certain conditions are met. For instance, if a post is not found, we can just toss a NotFoundException, and the application will handle it accordingly, but, not by showing a 500 error as usual, instead we're going to setup custom error handlers. You could alternatively use App::abort(404) or something along those lines, but I find that this method saves me many conditional statements and repeat code, as well as allowing me to adjust the implementation of error reporting in a single place very easily.

First let's define the custom Exceptions. Create a file in your app folder called errors.php

app/errors.php

These are very simple Exceptions, notice for the ValidationException, we can just pass it the failed validator instance and it will handle the error messages accordingly!

Now we need to define our error handlers that will be called when one of these Exceptions are thrown. These are basically Event listeners, whenever one of these exceptions are thrown, it's treated as an Event and calls the appropriate function. It's very simple to add logging or any other error handling procedures here.

app/filters.php

We now need to let our auto-loader know about these new files. So we must tell Composer where to check for them:

composer.json

Notice that we added the "app/errors.php" line.

We must now tell Composer to actually check for these files and include them in the auto-load registry.

Great, so we have completed our controllers and our repositories, the last two items in our MVRC that we have to take care of is the models and views, both of which are pretty straight forward.

app/models/Post.php

app/models/Comment.php

As far as views are concerned, I'm just going to mark up some simple bootstrap-friendly pages. Remember to change each files extension to .mustache though, since our generator thought that we would be using .blade.php. We're also going to create a few "partial" views using the Rails convention of prefixing them with an _ to signify a partial.

Note: I skipped a few views, as we will not be using them in this tutorial.

public/views/posts/index.mustache

For the index page view we'll just loop over all of our posts, showing the post partial for each.

public/views/posts/show.mustache

For the show view we'll show an entire post and its comments:

public/views/posts/_post.mustache

Here's the partial that we'll use to show a post in a list. This is used on our index view.

public/views/posts/_form.mustache

Here's the form partial needed to create a post, we'll use this from our API, but this could also be a useful view in an admin panel and other places, which is why we choose to make it a partial.

public/views/comments/_comment.mustache

Here's the comment partial which is used to represent a single comment in a list of comments:

public/views/comments/_form.mustache

The form needed to create a comment - both used in the API and the Show Post view:

public/views/layouts/_notification.mustache

And here's the helper view partial to allow us to show a notification:

Great, we have all of our API components in place. Let's run our unit tests to see where we're at!

Your first run of this test should pass with flying (green) colors. However, if you were to run this test again, you'll notice that it fails now with a handful of errors, and that is because our repository tests actually tested the database, and in doing so deleted some of the records our previous tests used to assert values. This is an easy fix, all we have to do is tell our tests that they need to re-seed the database after each test. In addition, we did not receive a noticable error for this, but we did not close Mockery after each test either, this is a requirement of Mockery that you can find in their docs. So let's add both missing methods.

Open up app/tests/TestCase.php and add the following two methods:

This is great, we now said that at every "setUp", which is run before each test, to re-seed the database. However we still have one problem, everytime you re-seed, it's only going to append new rows to the tables. Our tests are looking for items with a row ID of one, so we still have a few changes to make. We just need to tell the database to truncate our tables when seeding:

app/database/seeds/CommentsTableSeeder.php

Before we insert the new rows, we'll truncate the table, deleting all rows and resetting the auto-increment counter.

app/database/seeds/PostsTableSeeder.php

Now you should be able to run the tests any number of times and get passing tests each time! That means we have fulfilled our TDD cycle and we're not allowed to write anymore production code for our API!! Let's just commit our changes to our repo and move onto the Backbone application!


Backbone App

Now that we have completed all of the back-end work, we can move forward to creating a nice user interface to access all of that data. We'll keep this part of the project a little bit on the simpler side, and I warn you that my approach can be considered an opinionated one. I have seen many people with so many different methods for structuring a Backbone application. My trials and errors have led me to my current method, if you do not agree with it, my hope is that it may inspire you to find your own!

We're going to use the Mustache templating engine instead of Underscore, this will allow us to share our views between the client and server! The trick is in how you load the views, we're going to use AJAX in this tutorial, but it's just as easy to load them all into the main template, or precompile them.

Router

First we'll get our router going. There are two parts to this, the Laravel router, and the Backbone router.

Laravel Router

There are two main approaches we can take here:

Approach #1: The catch-all

Remember I told you when you were adding the resource routes that it was important that you placed them ABOVE the app route?? The catch-all method is the reason for that statement. The overall goal of this method is to have any routes that have not found a match in Laravel, be caught and sent to Backbone. Implementing this method is easy:

app/routes.php

Now, every route other than our API routes will render our app view.

In addition, if you have a multi-page app (several single page apps), you can define several of these catch-alls:

Note: Keep in mind the '/' before {path?}. If that slash is there, it'll be required in the URL (with the exception of the index route), sometimes this is desired and sometimes not.

Approach #2:

Since our front and back end share views... wouldn't it be extremely easy to just define routes in both places? You can even do this in addition to the catch-all approach if you want.

The routes that we're going to end up defining for the app are simply:

app/routes.php

Pretty cool huh?! Regardless of which method we use, or the combination of both, your Backbone router will end up mostly the same.

Notice that we're using our Repository again, this is yet another reason why Repositories are a useful addition to our framework. We can now run almost all of the logic that the controller does, but without repeating hardly any of the code!

Keep in mind a few things while choosing which method to use, if you use the catch-all, it will do just like the name implies... catch-ALL. This means there is no such thing as a 404 on your site anymore. No matter the request, its landing on the app page (unless you manually toss an exception somewhere such as your repository). The inverse is, with defining each route, now you have two sets of routes to manage. Both methods have their ups and downs, but both are equally easy to deal with.

Base View

One view to rule them all! This BaseView is the view that all of our other Views will inherit from. For our purposes, this view has but one job... templating! In a larger app this view is a good place to put other shared logic.

We'll simply extend Backbone.View and add a template function that will return our view from the cache if it exists, or get it via AJAX and place it in the cache. We have to use synchronous AJAX due to the way that Mustache.js fetches partials, but since we're only retrieving these views if they are not cached, we shouldn't receive much of a performance hit here.

PostView

The PostView renders a single blog post:

Partial Views

We'll need a few views to render partials. We mainly just need to tell the view which template to use and that it should extend our view that provides the method to fetch our template.

Blog View

This is our overall application view. It contains our configuration logic, as well as handling the fetching of our PostCollection. We also setup a cool little infinite scroll feature. Notice how we're using jQuery promises to ensure that the fetching of our collection has completed prior to rendering the view.

PostCollection

Setup our PostCollection - we just need to tell the Collection the URL it should use to fetch its contents.

Blog Router

Notice that we're not instantiating new instances of our views, we're merely telling them to render. Our initialize functions are designed to only be ran once, as we don't want them to run but once, on page load.

Notifications Collection

We're just going to setup a simple Collection to store user notifications:

NotificationsView

This view will handle the displaying and hiding of user notifications:

Error Handling

Since we used the custom exception handlers for our API, it makes it very easy to handle any error our API may throw. Very similar to the way we defined our event listeners for our API in the app/filters.php file, we'll define event listeners for our app here. Each code that could be thrown can just show a notification very easily!


Event Listeners

We'll need a few global event listeners to help us navigate through our app without refreshing the page. We mainly just hijack the default behavior and call Backbone.history.navigate(). Notice how on our first listener, we're specifying the selector to only match those that don't have a data attribute of bypass. This will allow us to create links such as <a href="/some/non-ajax/page" data-bypass="true">link</a> that will force the page to refresh. We could also go a step further here and check whether the link is a local one, as opposed to a link to another site.

Start The App

Now we just need to boot the app, passing in any config values that we need. Notice the line that checks for the silentRouter global variable, this is kind of a hacky way to be able to use both back-end routing methods at the same time. This allows us to define a variable in the view called silentRouter and set it to true, meaning that the router should not actually engage the backbone route, allowing our back-end to handle the initial rendering of the page, and just wait for any needed updates or AJAX.


Conclusion

Notice that for the Backbone portion of our app, all we had to do was write some Javascript that knew how to interact with the pre-existing portions of our application? That's what I love about this method! It may seem like we had a lot of steps to take to get to that portion of things, but really, most of that work was just a foundation build-up. Once we got that initial foundation in place, the actual application logic falls together very simply.

Try adding another feature to this blog, such as User listings and info. The basic steps you would take would be something like this:

  • Use the generator tool to create a new "User" resource.
  • Make the necessary modifications to ensure that the UserController is in the V1 API group.
  • Create your Repository and setup the proper IoC bindings in app/routes.php.
  • Write your Controller tests one at a time using Mockery for the repository, following each test up with the proper implementation to make sure that test passes.
  • Write your Repository tests one at a time, again, following each test up with the implementation.
  • Add in the new functionality to your Backbone App. I suggest trying two different approaches to the location of the User views. Decide for yourself which is the better implementation.
    • First place them in their own routes and Main view.
    • Then try incorporating them into the overall BlogView.

I hope this gave you some insight into creating a scalable single page app and API using Laravel 4 and Backbone.js. If you have any questions, please ask them in the comment section below!

Tags:

Comments

Related Articles