Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 14, 2013 05:33 am GMT

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.

mkdir project && cd projectgit init

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.

git remote add laravel https://github.com/laravel/laravelgit fetch laravelgit merge laravel/developgit add . && git commit -am "commit the laravel application structure"

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

{  "require": {    "laravel/framework": "4.0.*",    "way/generators": "dev-master",    "twitter/bootstrap": "dev-master",    "conarwelsh/mustache-l4": "dev-master"  },  "require-dev": {    "phpunit/phpunit": "3.7.*",    "mockery/mockery": "0.7.*"  },  "autoload": {    "classmap": [      "app/commands",      "app/controllers",      "app/models",      "app/database/migrations",      "app/database/seeds",      "app/tests/TestCase.php"    ]  },  "scripts": {    "post-update-cmd": "php artisan optimize"  },  "minimum-stability": "dev"}

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".

composer install --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

...'Way\Generators\GeneratorsServiceProvider','Conarwelsh\MustacheL4\MustacheL4ServiceProvider',...

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

/*|--------------------------------------------------------------------------| Detect The Application Environment|--------------------------------------------------------------------------|| Laravel takes a dead simple approach to your application environments| so you can just specify a machine name or HTTP host that matches a| given environment, then we will automatically detect it for you.|*/$env = $app->detectEnvironment(array(  'local' => array('your-machine-name'),));

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

'paths' => array(__DIR__.'/../../public/views'),

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.

chmod -R 755 app/storage

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

{  "name": "nettuts-laravel4-and-backbone",  "version": "0.0.1",  "private": true,  "dependencies": {    "underscore": "*",    "backbone": "*",    "mustache": "*"  }}

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.

cd publicnpm installcd ..

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:

mkdir public/views public/views/layouts public/js public/css && touch public/css/styles.less public/js/app.js public/views/app.mustache

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
cp vendor/twitter/bootstrap/docs/assets/js/html5shiv.js public/js/html5shiv.jscp vendor/twitter/bootstrap/docs/assets/js/bootstrap.min.js public/js/bootstrap.min.js

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:

cp vendor/twitter/bootstrap/docs/examples/starter-template.html public/views/layouts/application.blade.php

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.

/** * Import Twitter Bootstrap Base File ****************************************************************************************** */@import "../../vendor/twitter/bootstrap/less/bootstrap";/** * Define App Styles * Do this before the responsive include, so that it can override properly as needed. ****************************************************************************************** */body {  padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */}/* this will set the position of our alerts */#notifications {  width: 300px;  position: fixed;  top: 50px;  left: 50%;  margin-left: -150px;  text-align: center;}/** * Import Bootstrap's Responsive Overrides * now we allow bootstrap to set the overrides for a responsive layout ****************************************************************************************** */@import "../../vendor/twitter/bootstrap/less/responsive";/** * Define our variables last, any variable declared here will be used in the includes above * which means that we can override any of the variables used in the bootstrap files easily * without modifying any of the core bootstrap files ****************************************************************************************** */// Scaffolding// -------------------------@bodyBackground:    #f2f2f2;@textColor:       #575757;// Links// -------------------------@linkColor:       #41a096;// Typography// -------------------------@sansFontFamily:    Arial, Helvetica, sans-serif;

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.

//alias the global object//alias jQuery so we can potentially use other libraries that utilize $//alias Backbone to save us on some typing(function(exports, $, bb){  //document ready  $(function(){    /**     ***************************************     * Cached Globals     ***************************************     */    var $window, $body, $document;    $window  = $(window);    $document = $(document);    $body   = $('body');  });//end document ready}(this, jQuery, Backbone));

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.

<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <title>Laravel4 & Backbone | Nettuts</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="A single page blog built using Backbone.js, Laravel, and Twitter Bootstrap"> <meta name="author" content="Conar Welsh"> <link href="{{ asset('css/styles.css') }}" rel="stylesheet"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="{{ asset('js/html5shiv.js') }}"></script> <![endif]--></head><body> <div id="notifications"> </div> <div class="navbar navbar-inverse navbar-fixed-top">  <div class="navbar-inner">   <div class="container">    <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">     <span class="icon-bar"></span>     <span class="icon-bar"></span>     <span class="icon-bar"></span>    </button>    <a class="brand" href="#">Nettuts Tutorial</a>    <div class="nav-collapse collapse">     <ul class="nav">      <li class="active"><a href="#">Blog</a></li>     </ul>    </div><!--/.nav-collapse -->   </div>  </div> </div> <div class="container" data-role="main">  {{--since we are using mustache as the view, it does not have a concept of sections like blade has, so instead of using @yield here, our nested view will just be a variable that we can echo--}}  {{ $content }} </div> <!-- /container --> <!-- Placed at the end of the document so the pages load faster --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- use Google CDN for jQuery to hopefully get a cached copy --> <script src="{{ asset('node_modules/underscore/underscore-min.js') }}"></script> <script src="{{ asset('node_modules/backbone/backbone-min.js') }}"></script> <script src="{{ asset('node_modules/mustache/mustache.js') }}"></script> <script src="{{ asset('js/bootstrap.min.js') }}"></script> <script src="{{ asset('js/app.js') }}"></script> @yield('scripts')</body></html>

public/views/app.mustache

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

<dl>  <dt>Q. What did Biggie say when he watched inception?</dt>  <dd>A. "It was all a dream!"</dd></dl>

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:

View::make('view.path')->nest($sectionName, $nestedViewPath, $viewVariables);

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.

<?php//backbone app routeRoute::get('/', function(){  //change our view name to the view we created in a previous step  //notice that we do not need to provide the .mustache extension  return View::make('layouts.application')->nest('content', 'app');});

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!

php artisan serve

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:

<?php//create a group of routes that will belong to APIv1Route::group(array('prefix' => 'v1'), function(){  //... insert API routes here...});

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.

sudo chmod -R 755 vendor/way/generators/src/Way/

Run the generate:resource command

php artisan generate:resource post --fields="title:string, content:text, author_name:string"php artisan generate:resource comment --fields="content:text, author_name:string, post_id:integer"

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

mv app/views/posts public/views/postsmv app/views/comments public/views/comments

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.

<?php//create a group of routes that will belong to APIv1Route::group(array('prefix' => 'v1'), function(){  //... insert API routes here...  Route::resource('posts', 'V1\PostsController'); //notice the namespace  Route::resource('posts.comments', 'V1\PostsCommentsController'); //notice the namespace, and the nesting});//backbone app routeRoute::get('/', function(){  //change our view name to the view we created in a previous step  //notice that we do not need to provide the .mustache extension  return View::make('layouts.application')->nest('content', 'app');});

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.

mkdir app/controllers/V1mv app/controllers/PostsController.php app/controllers/V1/mv app/controllers/CommentsController.php app/controllers/V1/PostsCommentsController.php

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

<?php//use our new namespacenamespace V1;//import classes that are not in this new namespaceuse BaseController;class PostsController extends BaseController {

app/controllers/PostsCommentsController.php

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

<?php//use our new namespacenamespace V1;//import classes that are not in this new namespaceuse BaseController;//rename our controller classclass PostsCommentsController extends BaseController {

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:

mkdir app/repositories

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

{  "require": {    "laravel/framework": "4.0.*",    "way/generators": "dev-master",    "twitter/bootstrap": "dev-master",    "conarwelsh/mustache-l4": "dev-master"  },  "require-dev": {    "phpunit/phpunit": "3.7.*",    "mockery/mockery": "0.7.*"  },  "autoload": {    "classmap": [      "app/commands",      "app/controllers",      "app/models",      "app/database/migrations",      "app/database/seeds",      "app/tests/TestCase.php",      "app/repositories"    ]  },  "scripts": {    "post-update-cmd": "php artisan optimize"  },  "minimum-stability": "dev"}

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

<?phpclass PostsTableSeeder extends Seeder {  public function run()  {    $posts = array(      array(        'title'    => 'Test Post',        'content'   => 'Lorem ipsum Reprehenderit velit est irure in enim in magna aute occaecat qui velit ad.',        'author_name' => 'Conar Welsh',        'created_at' => date('Y-m-d H:i:s'),        'updated_at' => date('Y-m-d H:i:s'),      ),      array(        'title'    => 'Another Test Post',        'content'   => 'Lorem ipsum Reprehenderit velit est irure in enim in magna aute occaecat qui velit ad.',        'author_name' => 'Conar Welsh',        'created_at' => date('Y-m-d H:i:s'),        'updated_at' => date('Y-m-d H:i:s'),      ),    );    // Uncomment the below to run the seeder    DB::table('posts')->insert($posts);  }}

app/database/seeds/CommentsTableSeeder.php

<?phpclass CommentsTableSeeder extends Seeder {  public function run()  {    $comments = array(      array(        'content'   => 'Lorem ipsum Nisi dolore ut incididunt mollit tempor proident eu velit cillum dolore sed',        'author_name' => 'Testy McTesterson',        'post_id'   => 1,        'created_at' => date('Y-m-d H:i:s'),        'updated_at' => date('Y-m-d H:i:s'),      ),      array(        'content'   => 'Lorem ipsum Nisi dolore ut incididunt mollit tempor proident eu velit cillum dolore sed',        'author_name' => 'Testy McTesterson',        'post_id'   => 1,        'created_at' => date('Y-m-d H:i:s'),        'updated_at' => date('Y-m-d H:i:s'),      ),      array(        'content'   => 'Lorem ipsum Nisi dolore ut incididunt mollit tempor proident eu velit cillum dolore sed',        'author_name' => 'Testy McTesterson',        'post_id'   => 2,        'created_at' => date('Y-m-d H:i:s'),        'updated_at' => date('Y-m-d H:i:s'),      ),    );    // Uncomment the below to run the seeder    DB::table('comments')->insert($comments);  }}

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

composer dump-autoload

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

php artisan migrate --seed

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:

vendor/phpunit/phpunit/phpunit.php

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.

rm app/tests/ExampleTest.php

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:

mkdir app/tests/controllers app/tests/repositories

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:

App::instance($classToReplace, $instanceOfClassToReplaceWith);

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

<?phpclass CommentsControllerTest extends TestCase {  /**   ************************************************************************   * Basic Route Tests   * notice that we can use our route() helper here!   ************************************************************************   */  //test that GET /v1/posts/1/comments returns HTTP 200  public function testIndex()  {    $response = $this->call('GET', route('v1.posts.comments.index', array(1)) );    $this->assertTrue($response->isOk());  }  //test that GET /v1/posts/1/comments/1 returns HTTP 200  public function testShow()  {    $response = $this->call('GET', route('v1.posts.comments.show', array(1,1)) );    $this->assertTrue($response->isOk());  }  //test that GET /v1/posts/1/comments/create returns HTTP 200  public function testCreate()  {    $response = $this->call('GET', route('v1.posts.comments.create', array(1)) );    $this->assertTrue($response->isOk());  }  //test that GET /v1/posts/1/comments/1/edit returns HTTP 200  public function testEdit()  {    $response = $this->call('GET', route('v1.posts.comments.edit', array(1,1)) );    $this->assertTrue($response->isOk());  }  /**   *************************************************************************   * Tests to ensure that the controller calls the repo as we expect   * notice we are "Mocking" our repository   *   * also notice that we do not really care about the data or interactions   * we merely care that the controller is doing what we are going to want   * it to do, which is reach out to our repository for more information   *************************************************************************   */  //ensure that the index function calls our repository's "findAll" method  public function testIndexShouldCallFindAllMethod()  {    //create our new Mockery object with a name of CommentRepositoryInterface    $mock = Mockery::mock('CommentRepositoryInterface');    //inform the Mockery object that the "findAll" method should be called on it once    //and return a string value of "foo"    $mock->shouldReceive('findAll')->once()->andReturn('foo');    //inform our application that we have an instance that it should use    //whenever the CommentRepositoryInterface is requested    App::instance('CommentRepositoryInterface', $mock);    //call our controller route    $response = $this->call('GET', route('v1.posts.comments.index', array(1)));    //assert that the response is a boolean value of true    $this->assertTrue(!! $response->original);  }  //ensure that the show method calls our repository's "findById" method  public function testShowShouldCallFindById()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('findById')->once()->andReturn('foo');    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.comments.show', array(1,1)));    $this->assertTrue(!! $response->original);  }  //ensure that our create method calls the "instance" method on the repository  public function testCreateShouldCallInstanceMethod()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('instance')->once()->andReturn(array());    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.comments.create', array(1)));    $this->assertViewHas('comment');  }  //ensure that the edit method calls our repository's "findById" method  public function testEditShouldCallFindByIdMethod()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('findById')->once()->andReturn(array());    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.comments.edit', array(1,1)));    $this->assertViewHas('comment');  }  //ensure that the store method should call the repository's "store" method  public function testStoreShouldCallStoreMethod()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('store')->once()->andReturn('foo');    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('POST', route('v1.posts.comments.store', array(1)));    $this->assertTrue(!! $response->original);  }  //ensure that the update method should call the repository's "update" method  public function testUpdateShouldCallUpdateMethod()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('update')->once()->andReturn('foo');    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('PUT', route('v1.posts.comments.update', array(1,1)));    $this->assertTrue(!! $response->original);  }  //ensure that the destroy method should call the repositories "destroy" method  public function testDestroyShouldCallDestroyMethod()  {    $mock = Mockery::mock('CommentRepositoryInterface');    $mock->shouldReceive('destroy')->once()->andReturn(true);    App::instance('CommentRepositoryInterface', $mock);    $response = $this->call('DELETE', route('v1.posts.comments.destroy', array(1,1)));    $this->assertTrue( empty($response->original) );  }}

app/tests/controllers/PostsControllerTest.php

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

<?phpclass PostsControllerTest extends TestCase {  /**   * Test Basic Route Responses   */  public function testIndex()  {    $response = $this->call('GET', route('v1.posts.index'));    $this->assertTrue($response->isOk());  }  public function testShow()  {    $response = $this->call('GET', route('v1.posts.show', array(1)));    $this->assertTrue($response->isOk());  }  public function testCreate()  {    $response = $this->call('GET', route('v1.posts.create'));    $this->assertTrue($response->isOk());  }  public function testEdit()  {    $response = $this->call('GET', route('v1.posts.edit', array(1)));    $this->assertTrue($response->isOk());  }  /**   * Test that controller calls repo as we expect   */  public function testIndexShouldCallFindAllMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('findAll')->once()->andReturn('foo');    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.index'));    $this->assertTrue(!! $response->original);  }  public function testShowShouldCallFindById()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('findById')->once()->andReturn('foo');    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.show', array(1)));    $this->assertTrue(!! $response->original);  }  public function testCreateShouldCallInstanceMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('instance')->once()->andReturn(array());    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.create'));    $this->assertViewHas('post');  }  public function testEditShouldCallFindByIdMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('findById')->once()->andReturn(array());    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('GET', route('v1.posts.edit', array(1)));    $this->assertViewHas('post');  }  public function testStoreShouldCallStoreMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('store')->once()->andReturn('foo');    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('POST', route('v1.posts.store'));    $this->assertTrue(!! $response->original);  }  public function testUpdateShouldCallUpdateMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('update')->once()->andReturn('foo');    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('PUT', route('v1.posts.update', array(1)));    $this->assertTrue(!! $response->original);  }  public function testDestroyShouldCallDestroyMethod()  {    $mock = Mockery::mock('PostRepositoryInterface');    $mock->shouldReceive('destroy')->once()->andReturn(true);    App::instance('PostRepositoryInterface', $mock);    $response = $this->call('DELETE', route('v1.posts.destroy', array(1)));    $this->assertTrue( empty($response->original) );  }}

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!

<?phpclass EloquentCommentRepositoryTest extends TestCase {  public function setUp()  {    parent::setUp();    $this->repo = App::make('EloquentCommentRepository');  }  public function testFindByIdReturnsModel()  {    $comment = $this->repo->findById(1,1);    $this->assertTrue($comment instanceof Illuminate\Database\Eloquent\Model);  }  public function testFindAllReturnsCollection()  {    $comments = $this->repo->findAll(1);    $this->assertTrue($comments instanceof Illuminate\Database\Eloquent\Collection);  }  public function testValidatePasses()  {    $reply = $this->repo->validate(array(      'post_id'   => 1,      'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.',      'author_name' => 'Testy McTesterson'    ));    $this->assertTrue($reply);  }  public function testValidateFailsWithoutContent()  {    try {      $reply = $this->repo->validate(array(        'post_id'   => 1,        'author_name' => 'Testy McTesterson'      ));    }    catch(ValidationException $expected)    {      return;    }    $this->fail('ValidationException was not raised');  }  public function testValidateFailsWithoutAuthorName()  {    try {      $reply = $this->repo->validate(array(        'post_id'   => 1,        'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.'      ));    }    catch(ValidationException $expected)    {      return;    }    $this->fail('ValidationException was not raised');  }  public function testValidateFailsWithoutPostId()  {    try {      $reply = $this->repo->validate(array(        'author_name' => 'Testy McTesterson',        'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.'      ));    }    catch(ValidationException $expected)    {      return;    }    $this->fail('ValidationException was not raised');  }  public function testStoreReturnsModel()  {    $comment_data = array(      'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.',      'author_name' => 'Testy McTesterson'    );    $comment = $this->repo->store(1, $comment_data);    $this->assertTrue($comment instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($comment->content === $comment_data['content']);    $this->assertTrue($comment->author_name === $comment_data['author_name']);  }  public function testUpdateSaves()  {    $comment_data = array(      'content' => 'The Content Has Been Updated'    );    $comment = $this->repo->update(1, 1, $comment_data);    $this->assertTrue($comment instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($comment->content === $comment_data['content']);  }  public function testDestroySaves()  {    $reply = $this->repo->destroy(1,1);    $this->assertTrue($reply);    try {      $this->repo->findById(1,1);    }    catch(NotFoundException $expected)    {      return;    }    $this->fail('NotFoundException was not raised');  }  public function testInstanceReturnsModel()  {    $comment = $this->repo->instance();    $this->assertTrue($comment instanceof Illuminate\Database\Eloquent\Model);  }  public function testInstanceReturnsModelWithData()  {    $comment_data = array(      'title' => 'Un-validated title'    );    $comment = $this->repo->instance($comment_data);    $this->assertTrue($comment instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($comment->title === $comment_data['title']);  }}

app/tests/repositories/EloquentPostRepositoryTest.php

<?phpclass EloquentPostRepositoryTest extends TestCase {  public function setUp()  {    parent::setUp();    $this->repo = App::make('EloquentPostRepository');  }  public function testFindByIdReturnsModel()  {    $post = $this->repo->findById(1);    $this->assertTrue($post instanceof Illuminate\Database\Eloquent\Model);  }  public function testFindAllReturnsCollection()  {    $posts = $this->repo->findAll();    $this->assertTrue($posts instanceof Illuminate\Database\Eloquent\Collection);  }  public function testValidatePasses()  {    $reply = $this->repo->validate(array(      'title'    => 'This Should Pass',      'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.',      'author_name' => 'Testy McTesterson'    ));    $this->assertTrue($reply);  }  public function testValidateFailsWithoutTitle()  {    try {      $reply = $this->repo->validate(array(        'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.',        'author_name' => 'Testy McTesterson'      ));    }    catch(ValidationException $expected)    {      return;    }    $this->fail('ValidationException was not raised');  }  public function testValidateFailsWithoutAuthorName()  {    try {      $reply = $this->repo->validate(array(        'title'    => 'This Should Pass',        'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.'      ));    }    catch(ValidationException $expected)    {      return;    }    $this->fail('ValidationException was not raised');  }  public function testStoreReturnsModel()  {    $post_data = array(      'title'    => 'This Should Pass',      'content'   => 'Lorem ipsum Fugiat consectetur laborum Ut consequat aliqua.',      'author_name' => 'Testy McTesterson'    );    $post = $this->repo->store($post_data);    $this->assertTrue($post instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($post->title === $post_data['title']);    $this->assertTrue($post->content === $post_data['content']);    $this->assertTrue($post->author_name === $post_data['author_name']);  }  public function testUpdateSaves()  {    $post_data = array(      'title' => 'The Title Has Been Updated'    );    $post = $this->repo->update(1, $post_data);    $this->assertTrue($post instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($post->title === $post_data['title']);  }  public function testDestroySaves()  {    $reply = $this->repo->destroy(1);    $this->assertTrue($reply);    try {      $this->repo->findById(1);    }    catch(NotFoundException $expected)    {      return;    }    $this->fail('NotFoundException was not raised');  }  public function testInstanceReturnsModel()  {    $post = $this->repo->instance();    $this->assertTrue($post instanceof Illuminate\Database\Eloquent\Model);  }  public function testInstanceReturnsModelWithData()  {    $post_data = array(      'title' => 'Un-validated title'    );    $post = $this->repo->instance($post_data);    $this->assertTrue($post instanceof Illuminate\Database\Eloquent\Model);    $this->assertTrue($post->title === $post_data['title']);  }}

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

vendor/phpunit/phpunit/phpunit.php

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:
Route::get('/', array(  'uses' => 'SomeController@action'));

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

<?phpnamespace V1;use BaseController; use PostRepositoryInterface; use Input;use View;class PostsController extends BaseCo

Original Link: http://feedproxy.google.com/~r/nettuts/~3/sp8nPXhAUws/

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code