<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Culttt &#187; Code</title>
	<atom:link href="http://culttt.com/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://culttt.com</link>
	<description>Articles on business, technology and the Internet</description>
	<lastBuildDate>Fri, 24 May 2013 07:30:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Getting started with testing Laravel 4 Models</title>
		<link>http://culttt.com/2013/05/20/getting-started-with-testing-laravel-4-models/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-testing-laravel-4-models</link>
		<comments>http://culttt.com/2013/05/20/getting-started-with-testing-laravel-4-models/#comments</comments>
		<pubDate>Mon, 20 May 2013 07:28:38 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=3132</guid>
		<description><![CDATA[<p>Last week I looked at what are Models in MVC applications, what are the characteristics of a Model and how to make your first Model in Laravel 4. An integral part of writing high quality web applications is having automated tests that can ensure that your entire application is functioning correctly. In a Continuous Integration [...]</p><p><a href="http://culttt.com/2013/05/20/getting-started-with-testing-laravel-4-models/">Getting started with testing Laravel 4 Models</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/05/Getting-started-with-testing-Laravel-4-Models.jpg" alt="Getting started with testing Laravel 4 Models" /><br />
Last week I looked at what are Models in MVC applications, what are the characteristics of a Model and how to make your first Model in Laravel 4.</p>
<p>An integral part of writing high quality web applications is having automated tests that can ensure that your entire application is functioning correctly. In a <a href="http://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration (CI)</a> set up, having automated tests is extremely important to ensure that new changes don&#8217;t break the current code.</p>
<p>This isn&#8217;t a tutorial on Test Driven Development, so I&#8217;m going to assume that you already know what it is, how it is structured and what we are trying to achieve. If this is all new to you, take a look at my tutorial <a href="http://culttt.com/2013/03/11/what-is-test-driven-development/">What is Test Driven Development?</a>.</p>
<p>If you haven&#8217;t already read last week&#8217;s tutorial, you will probably want to read that first as it gives a lot of background to what I&#8217;m going to be doing in this tutorial, <a href="http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model">Setting up your first Laravel 4 Model</a>.</p>
<h2>Installing PHPUnit</h2>
<p>In order to write automated tests, we need to install a fantastic package called <a href="https://github.com/sebastianbergmann/phpunit/">PHPUnit</a>.</p>
<p>If you are new to PHPUnit, you might want to read my introductory tutorial <a href="http://culttt.com/2013/03/13/getting-started-with-phpunit/">Getting started with PHPUnit</a> first.</p>
<p>To install PHPUnit, add the following line to your <code>composer.json</code> file.</p>
<pre class="brush: jscript; title: ; notranslate">
{
  &quot;require-dev&quot;: {
    &quot;phpunit/phpunit&quot;: &quot;3.7.*&quot;
  }
}
</pre>
<p>Next run the <code>composer update</code> command to install the package:</p>
<pre class="brush: bash; title: ; notranslate">
$ composer update
</pre>
<p>Now that you have PHPUnit installed, you can run automated tests from the command line. Laravel comes with one example test already set up. To make sure you have PHPUnit correctly set up, run the following command from Terminal:</p>
<pre class="brush: bash; title: ; notranslate">
$ vendor/bin/phpunit
</pre>
<p>You should get the following line returned if everything went ok:</p>
<pre class="brush: bash; title: ; notranslate">
OK (1 test, 2 assertions)
</pre>
<p>To make things easier for myself, I like to set an alias to PHPUnit so I don&#8217;t have to type of the <code>vendor/bin</code> bit every time I want to run the command.</p>
<pre class="brush: bash; title: ; notranslate">
alias phpunit='vendor/bin/phpunit'
</pre>
<h2>Writing your first test</h2>
<p>When writing unit tests, you want to concentrate on only one thing in particular. So for each Model that you have in your system, you should have exactly one test file that contains all of the automated tests. If you find yourself writing tests for things in more than one place, you will probably be doing something wrong.</p>
<p>All of the tests in a Laravel application are kept under <code>app/tests</code>.</p>
<p>If you look inside that directory, you should find the <code>ExampleTest.php</code>. When we ran the <code>phpunit</code> command from the command line earlier, this is the file of tests that was run. As you can see, there is one test with 2 assertions. You can just delete this file.</p>
<p>Laravel doesn&#8217;t force you to structure your tests directory in any particular way. You can keep all of your tests under the tests directory, or you can put them in more specific sub folders. I&#8217;m going to be putting my tests in sub folders for <em>Models</em> and <em>Controllers</em>, but I might change this in the future. For example, a common structure is to separate your test files into <code>unit</code>, <code>functional</code> and <code>integration</code> directories, but at the end of the day, it doesn&#8217;t really matter.</p>
<p>So create a new directory called models <code>app/tests/models</code> and create a new file under that directory called <code>UserTest.php</code>.</p>
<p>Copy the following code to create your User Test file:</p>
<pre class="brush: php; title: ; notranslate">
class UserTest extends TestCase {}
</pre>
<p>As you can see, a test is simply a class that extends from the <code>TestCase</code> class. If you look under the <code>app/tests</code> directory, you will see the <code>TestCase.php</code> file that we are extending from. This is simply how Laravel sets up the testing environment and extends from PHPUnit so that we can write tests with all of the right methods. You don&#8217;t need to worry about this, just make sure that all of your test classes extend from <code>TestCase</code> and everything will automatically work correctly.</p>
<p>Each individual test should be written as a public method. The name of the method should be a descriptive name of what you are testing for. For example:</p>
<pre class="brush: php; title: ; notranslate">
public function testThatTrueIsTrue()
{
  $this-&gt;assertTrue(true);
}
</pre>
<p>If you run <code>phpunit</code> once again you will see that this test passed successfully with one assertion.</p>
<pre class="brush: bash; title: ; notranslate">
OK (1 test, 1 assertion)
</pre>
<h2>Setting up the test environment database</h2>
<p>As I mentioned in my <a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Migration</a> tutorial, Laravel makes it incredibly easy to switch out databases. This means for example, we can use a different database when in the <code>testing</code> environment, but we don&#8217;t actually have to change any of our code.</p>
<p>Under the <code>app/config/testing</code> directory, create a new file called <code>database.php</code> and copy the following configuration details:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
return array(
  'default' =&gt; 'sqlite',
  'connections' =&gt; array(
    'sqlite' =&gt; array(
    	'driver'   =&gt; 'sqlite',
    	'database' =&gt; ':memory:',
    	'prefix'   =&gt; ''
  	),
  )
);
</pre>
<p>Now whenever your application is in the <code>testing</code> environment, Laravel will automatically use the SQLite in-memory database instead of hitting your actual database.</p>
<p>Why is this such a good thing? Testing with an in-memory database is much quicker than hitting an actual database. It also prevents the problem of having left over test data in your database every time you run your tests.</p>
<p>Next we need to hijack the <code>TestCase</code> class to finish off the set up for using an in-memory database. This is because we need to migrate the database at the start of each test because the database will be empty to begin with.</p>
<p>Add the following two methods to your TestCase class:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class TestCase extends Illuminate\Foundation\Testing\TestCase {
 
  /**
   * Default preparation for each test
   */
  public function setUp()
  {
    parent::setUp();
 
    $this-&gt;prepareForTests();
  }
 
  /**
   * Creates the application.
   *
   * @return Symfony\Component\HttpKernel\HttpKernelInterface
   */
  public function createApplication()
  {
    $unitTesting = true;
 
    $testEnvironment = 'testing';
 
    return require __DIR__.'/../../start.php';
  }
 
  /**
   * Migrate the database
   */
  private function prepareForTests()
  {
    Artisan::call('migrate');
  }
}
</pre>
<p>I discovered this technique after reading this fantastic post <a href="http://net.tutsplus.com/tutorials/php/testing-like-a-boss-in-laravel-models/">Testing Like a Boss in Laravel: Models</a> by <a href="http://www.zizaco.net">Zizaco Zizuini</a>. We will be using more of Zizaco&#8217;s packages over the course of creating Cribbb, so go and <a href="https://github.com/Zizaco">checkout his work</a> and give him mad props for being an awesome contributor to the Laravel community.</p>
<h2>Testing the User Model</h2>
<p>Now that we have everything set up, we can start writing some tests. Currently our User model only really has validation that we can write tests for.</p>
<p>The first thing we will test for is that a username is a required field:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Username is required
 */
public function testUsernameIsRequired()
{
  // Create a new User
  $user = new User;
  $user-&gt;email = &quot;phil@ipbrown.com&quot;;
  $user-&gt;password = &quot;password&quot;;
  $user-&gt;password_confirmation = &quot;password&quot;;

  // User should not save
  $this-&gt;assertFalse($user-&gt;save());

  // Save the errors
  $errors = $user-&gt;errors()-&gt;all();

  // There should be 1 error
  $this-&gt;assertCount(1, $errors);

  // The username error should be set
  $this-&gt;assertEquals($errors[0], &quot;The username field is required.&quot;);
}
</pre>
<p>So first we create a new user that does not have a username. </p>
<p>Next, we attempt to save the user and <em>we assert that the return value is</em> <code>false</code>.</p>
<p>Next, we grab the errors and we make sure there is only one.</p>
<p>And finally we assert that the correct error has been set.</p>
<p>Now if you run PHPUnit again, you should get the following response:</p>
<pre class="brush: bash; title: ; notranslate">
$ phpunit
$ OK (1 test, 3 assertions)
</pre>
<p>And that is how you would write a validation test for the username property of the User model. Now strictly speaking, you shouldn&#8217;t have to write tests for your validation because we are using the Ardent package that will already have these tests. But, I think writing validation tests is a nice and easy way to get into thinking in the mindset of Test Driven Development.</p>
<h2>Conclusion</h2>
<p>That was an introductory tutorial on setting up your automated tests in a Laravel project. Hopefully you now have a good understanding on why you need automated tests as well as how to structure them and how to run them.</p>
<p>A good analogy for automated testing is that it is like having breaks on your car. If a car didn&#8217;t have breaks, the driver would have to drive very slowly because it would be dangerous. Automated testing allows you as a developer to work much quicker because it provides you with a safety net if something goes wrong.</p>
<p>This is a series of posts in building an entire Open Source application called <a href="http://cribbb.com">Cribbb</a>. All of the tutorials will be free to web, and all of the code is available on <a href="https://github.com/philipbrown/cribbb">GitHub</a>.</p>
<p>So far I&#8217;ve covered:</p>
<ol>
<li><a href="http://culttt.com/2013/04/29/getting-started-with-laravel-4/">Getting started with Laravel 4</a></li>
<li><a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Laravel 4 Migrations</a></li>
<li><a href="http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/">Setting up your first Laravel 4 Model</a></li>
</ol>
<p>In next Monday&#8217;s tutorial we will be looking at writing more advanced automated tests using fixtures!</p>
<p><a href="http://culttt.com/2013/05/20/getting-started-with-testing-laravel-4-models/">Getting started with testing Laravel 4 Models</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/05/20/getting-started-with-testing-laravel-4-models/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up your first Laravel 4 Model</title>
		<link>http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setting-up-your-first-laravel-4-model</link>
		<comments>http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/#comments</comments>
		<pubDate>Mon, 13 May 2013 07:29:20 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Cribbb]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=3104</guid>
		<description><![CDATA[<p>Model-View-Controller (MVC) is a very common design pattern in modern web applications. The wide usage and acceptance of the design pattern means that many of the most popular web frameworks are built around this architecture. Laravel 4 is one such framework that uses the MVC design pattern to cleanly separate the various aspects of a [...]</p><p><a href="http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/">Setting up your first Laravel 4 Model</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/05/Setting-up-your-first-Laravel-4-Model.jpg" alt="Setting up your first Laravel 4 Model" /><br />
<a href="http://culttt.com/2012/11/19/what-is-mvc-model-view-controller/">Model-View-Controller (MVC)</a> is a very common design pattern in modern web applications. The wide usage and acceptance of the design pattern means that many of the most popular web frameworks are built around this architecture.</p>
<p>Laravel 4 is one such framework that uses the MVC design pattern to cleanly separate the various aspects of a web application.</p>
<p>In this post we&#8217;re going to look at what exactly is a Model, what are the three crucial components of Business Logic, and how to set up your first Model in Laravel 4.</p>
<h2>What is a Model</h2>
<p>So what exactly is a Model? If we&#8217;re going to be building this entire application on Models, first we need to understand exactly what they are.</p>
<p>A Model should contain all of the <a href="http://en.wikipedia.org/wiki/Business_logic">Business Logic</a> of your application. Or in other words, how the application interacts with the database.</p>
<p>Business Logic is essentially:</p>
<ol>
<li>The real world objects that appear in your application</li>
<li>How those objects interact with each other</li>
<li>A set of rules for how those objects are accessed and updated</li>
</ol>
<p>So for example, Users will be an important object within Cribbb because it is a social application.</p>
<ol>
<li>We need to store details of our users and so we need a User Model and a User table in the database.</li>
<li>Users will be required to enter a username, email address and password as well as other profile details. In order to ensure they enter correctly formatted data, we need to validate their input.</li>
<li>Users will be able to create Posts. So a User can have many posts, and each Post should belong to a User.</li>
</ol>
<p>So as you can see, that is basically how Models work in MVC applications. Essentially each important thing in the application will probably need a Model. You will probably need to validate the data that is used in your Models, and any logic that relates Models to one another should be dealt with here.</p>
<h2>Creating the User model</h2>
<p>User authentication is a requirement in just about every modern web application. Instead of forcing you to write your own User Model, Laravel 4 actually comes with a User Model straight out of the box.</p>
<p>So if you go into the <code>app/models</code> directory, you should find the <code>User.php</code> file. All of your models should go into this folder and they should be named following the same convention. So say for example, you had a Model for Posts in your application, the Model file would be <code>app/models/Post.php</code>.</p>
<p>As a side note, you don&#8217;t have to follow this convention, there are ways around it, but I really don&#8217;t know why you would.</p>
<p>Anyway, if you open up the User model, you will see a fairly basic Model boilerplate.</p>
<h2>Anatomy of a Laravel Model</h2>
<p>So as I mentioned above, every Model should represent a table in the database. In order to interact with the database, we will need to extend the Model from <code>Eloquent</code>. <em>Eloquent</em> is an <a href="http://en.wikipedia.org/wiki/Active_record_pattern">ActiveRecord implementation</a> that comes with Laravel.</p>
<p>Each Model extends Eloquent and so it inherits all of Eloquent&#8217;s methods for interacting with the database:</p>
<pre class="brush: php; title: ; notranslate">
class User extends Eloquent {}
</pre>
<p>You will also notice that the default User Model implements two interfaces:</p>
<pre class="brush: php; title: ; notranslate">
implements UserInterface, RemindableInterface
</pre>
<p>I&#8217;m not going to cover interfaces or the remindable features that are built into Laravel&#8217;s User model today as I will talk about them more extensively in a later tutorial.</p>
<p>The next thing you will notice is the protected property <code>$table</code>:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';
</pre>
<p>As you can probably guess, this is simply declaring the name of the table that this model refers to. By default you don&#8217;t need to set this property as Laravel follows the <a href="http://en.wikipedia.org/wiki/Convention_over_configuration">convention of configuration</a> mantra. This basically means, if you call your model <em>User</em>, then Laravel will assume that your table name is <em>users</em>. Setting the <code>$table</code> property is useful when you want to give a table a name that does not follow this convention.</p>
<p>The <code>$hidden</code> property allows you to hide certain columns when returning an instance of the Model:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password');
</pre>
<p>This is simply an array of column names. This is useful when you want to return details of the user over a JSON API for example. You wouldn&#8217;t want to display the user&#8217;s password.</p>
<p>Next we need to protect against mass assignment. When you pass an array of data to the Model, the data is automatically <em>mass assigned</em> to the right columns. This is handy because it makes things a lot easier, but it also presents quite a serious security concern. For example, you wouldn&#8217;t want the a user to be able to change their user id as this should set automatically when the user is created and it should never change.</p>
<p>To protect against mass assignment, we need to specify which of the columns can be mass assigned. To do this, we need to set the <code>$fillable</code> property.</p>
<pre class="brush: php; title: ; notranslate">
protected $fillable = array('username', 'email');
</pre>
<p>This ensures only these fields can be mass assigned.</p>
<p>You can also set the <code>$guarded</code> property which <em>prevents</em> the listed columns from mass assignment. For example:</p>
<pre class="brush: php; title: ; notranslate">
protected $guarded = array('id', 'password');
</pre>
<p>And finally, the model comes with three simple methods for returning specific data items from the Model:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Get the unique identifier for the user.
 *
 * @return mixed
 */
public function getAuthIdentifier()
{
  return $this-&gt;getKey();
}

/**
 * Get the password for the user.
 *
 * @return string
 */
public function getAuthPassword()
{
  return $this-&gt;password;
}

/**
 * Get the e-mail address where password reminders are sent.
 *
 * @return string
 */
public function getReminderEmail()
{
  return $this-&gt;email;
}
</pre>
<h2>Validating in your Model</h2>
<p>All good applications require validating data at some point. Users are prone to make mistakes or enter incorrect data, and so you need to ensure that you enforce that only correct data is allowed to enter your system.</p>
<p>Laravel 4 comes with a fantastic <a href="http://four.laravel.com/docs/validation">Validation</a> package that makes creating and enforcing validation rules incredibly easy.</p>
<p>However, Laravel 4 does not enforce that you put your validation in your Models. A common bad practice is to place validation in the controller. This is bad because you are more than likely going to have to repeat that validation in multiple places throughout your application.</p>
<p>A much better place for your Validation is inside your Model because all interactions with the database must go through the Model, and so you will only need to write your rules once.</p>
<p>Due to Laravel 4 not enforcing where you put your Validation logic, I&#8217;m going to use an excellent package called <a href="https://github.com/laravelbook/ardent">Ardent</a> to handle all of that. Ardent allows you to create self-validating Models. This basically means, your Models will validate themselves whenever you interact with them so you don&#8217;t have to write validation logic.</p>
<h2>Installing Ardent through Composer</h2>
<p>Ardent is a Composer package so we can install it by simply adding it to the <code>composer.json</code> file.</p>
<p>Add the following line:</p>
<pre class="brush: jscript; title: ; notranslate">
{
  &quot;require&quot;: {
    &quot;laravelbook/ardent&quot;: &quot;dev-master&quot;
  }
}
</pre>
<p>And then run the following to update your project:</p>
<pre class="brush: bash; title: ; notranslate">
$ composer update
</pre>
<h2>Validating Models using Ardent</h2>
<p>In order to use Ardent, first we need to change where the User Model extends from.</p>
<h3>Extending from Ardent</h3>
<p>In <code>User.php</code> you will need to update the following two lines:</p>
<pre class="brush: php; title: ; notranslate">
// Add this line
use LaravelBook\Ardent\Ardent;

// Update this line
class User extends Ardent implements UserInterface, RemindableInterface {
</pre>
<p>Don&#8217;t worry through, all of Eloquent&#8217;s methods are still available through Ardent because Ardent is a direct decedent from Eloquent.</p>
<h3>Validation rules</h3>
<p>The next thing we need to do is to create a set of validation rules for each of the fields of the Model.</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Ardent validation rules
 */
public static $rules = array(
  'name' =&gt; 'required|between:4,16',
  'email' =&gt; 'required|email',
  'password' =&gt; 'required|alpha_num|min:8|confirmed',
  'password_confirmation' =&gt; 'required|alpha_num|between:4,8',
);
</pre>
<p>Ardent leverages <a href="http://four.laravel.com/docs/validation">Laravel&#8217;s Validation class</a> to create these easy to use validation rules. The validation rules for your model are simply stored as a public static array. As you can see from the values of the array, each rule is separated with a <em>pipe</em>.</p>
<p>For a full list of available validation rules, see <a href="http://four.laravel.com/docs/validation#available-validation-rules">this</a> section of the documentation.</p>
<h3>Using Ardent&#8217;s validation</h3>
<p>As I mentioned in the description of Ardent, all of your models will be &#8220;self validating&#8221;. This means your models will automatically reject input that does not pass your validation rules, without you actually having to do anything:</p>
<p>For example, the following will fail because I&#8217;m not supplying a  password confirmation:</p>
<pre class="brush: php; title: ; notranslate">
$user = new User;
$user-&gt;username = 'philipbrown';
$user-&gt;email = 'phil@ipbrown.com';
$user-&gt;password = 'deadgiveaway';
$user-&gt;save(); // returns false
</pre>
<p>However, the following will save successfully:</p>
<pre class="brush: php; title: ; notranslate">
$user = new User;
$user-&gt;username = 'philipbrown';
$user-&gt;email = 'phil@ipbrown.com';
$user-&gt;password = 'deadgiveaway';
$user-&gt;password_confirmation = 'deadgiveaway';
$user-&gt;save(); // returns true
</pre>
<p>Notice how you don&#8217;t have to validate any of the data yourself? If the validation fails, the model will simply not save.</p>
<h3>Automatically purge redundant data</h3>
<p>We don&#8217;t really want to save the <code>password_confirmation</code> data as this is just used for validation. To tell Ardent to just get rid of the redundant data like confirmation fields, we need to add the following line to the User model.</p>
<pre class="brush: php; title: ; notranslate">
public $autoPurgeRedundantAttributes = true;
</pre>
<h3>Validation example in action</h3>
<p>To quickly set up an example of all of this, we can simply define a new route that we can hit to see it in action.</p>
<p>Open <code>app/routes.php</code> and copy the following code:</p>
<pre class="brush: php; title: ; notranslate">
Route::get('/user', function()
{
  $user = new User;
  $user-&gt;username = 'philipbrown';
  $user-&gt;email = 'phil@ipbrown.com';
  $user-&gt;password = 'deadgiveaway';
  $user-&gt;password_confirmation = 'deadgiveaway';
  var_dump($user-&gt;save());
});
</pre>
<p>This will simply create a new route that you can hit in the browser. When you go to <em>/user</em>, Laravel will automatically create a new user and attempt to save it to the database. If the user is saved correctly, you should see <code>boolean true</code> outputted to the screen.</p>
<p>Save your <code>routes.php</code> and run the following command in Terminal to quickly set up the server:</p>
<pre class="brush: php; title: ; notranslate">
$ php artisan serve
</pre>
<p>Now go to <a href="http://localhost:8000/user">http://localhost:8000/user</a> to see your validation in action.</p>
<p>That was a very quick introduction to validating your Models in Laravel 4. I&#8217;ll be writing a much more in-depth article on the nitty gritty details of validation in the coming weeks.</p>
<h2>Laravel model relationships</h2>
<p>The third and final characteristic of a model is that they hold the information that describes how <em>business objects interact with one another</em>.</p>
<p>Describing the relationship of two models is as easy as creating a new method.</p>
<p>Add the following method to your <code>User.php</code> Model.</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Post relationship
 */
public function posts()
{
  return $this-&gt;hasMany('Post');
}
</pre>
<p>This extremely simple method is all you need to write in order to say <em>a user has many posts</em>.</p>
<p>Now of course, you will need to create the Post Model in order for this to work. I&#8217;m not going to go over creating the Post migration and model. Instead refer back to my <a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Laravel 4 Migrations</a> tutorial. For my Post model, I&#8217;m simply creating a <code>body</code> column and a <code>user_id</code> column. Here is the migration command that I ran.</p>
<pre class="brush: php; title: ; notranslate">
php artisan generate:migration create_posts_table --fields=&quot;body:text, user_id:integer&quot;
</pre>
<p>So your basic Post Model should look like this:</p>
<pre class="brush: php; title: ; notranslate">
class Post extends Eloquent {

  protected $fillable = array('body');

  public function user()
  {
    return $this-&gt;belongsTo('User');
  }
  
}
</pre>
<p>Notice how I have set the inverse of the relationship in the <code>user()</code> method. This is simply saying that each post belongs to a user.</p>
<p>Next, create a new test route in your <code>app/routes.php</code> and paste the following:</p>
<pre class="brush: php; title: ; notranslate">
// Create a new Post
$post = new Post(array('body' =&gt; 'Yada yada yada'));
// Grab User 1
$user = User::find(1);
// Save the Post
$user-&gt;posts()-&gt;save($post);
</pre>
<p>Now if you look in the posts table in your database, you should see that the post has saved and the <code>user_id</code> has automatically been assigned to the user&#8217;s id.</p>
<p>That was a very quick overview of creating relationships in your Laravel Models. Again, I will cover each of these areas in more detail as we add some complexity to Cribbb. To read more about Laravel Model relationships, have a look at the <a href="http://four.laravel.com/docs/eloquent#relationships">documentation</a>.</p>
<h2>Conclusion</h2>
<p>That was a quick overview of how to create Laravel Models. Hopefully you should have a firm understanding of the three important aspects of <em>business logic</em> that should be dealt with within your Models.</p>
<p>As I&#8217;ve mentioned a couple of times in this post, in future tutorials I will be going into much more depth on some of the intricacies of how Models work in web applications.</p>
<p>The observant amongst you will have noticed that I haven&#8217;t strictly followed <a href="http://culttt.com/2013/03/11/what-is-test-driven-development/">Test Driven Development</a>. However, don&#8217;t worry, I will be covering how to write Model tests using <a href="http://culttt.com/2013/03/13/getting-started-with-phpunit/">PHPUnit</a> next week!</p>
<p>This is a series of posts in building an entire Open Source application called <a href="http://cribbb.com">Cribbb</a>. All of the tutorials will be free to web, and all of the code is available on <a href="https://github.com/philipbrown/cribbb">GitHub</a>.</p>
<p>So far I&#8217;ve covered:</p>
<ol>
<li><a href="http://culttt.com/2013/04/29/getting-started-with-laravel-4/">Getting started with Laravel 4</a></li>
<li><a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Laravel 4 Migrations</a>
</ol>
<p>Come back next Monday as I look at how to write automated tests for your Models!</p>
<p><a href="http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/">Setting up your first Laravel 4 Model</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Laravel 4 Migrations</title>
		<link>http://culttt.com/2013/05/06/laravel-4-migrations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=laravel-4-migrations</link>
		<comments>http://culttt.com/2013/05/06/laravel-4-migrations/#comments</comments>
		<pubDate>Mon, 06 May 2013 07:30:11 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Cribbb]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=3080</guid>
		<description><![CDATA[<p>If you have ever worked on a big project with multiple developers, you will probably have found that keeping everyone&#8217;s database structure consistent can be a nightmare. For example, say one of your colleagues adds a new feature, and in doing so, is required to add a new column to the database. They commit their [...]</p><p><a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Laravel 4 Migrations</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/05/Laravel-4-Migrations.jpg" alt="Laravel 4 Migrations" /><br />
If you have ever worked on a big project with multiple developers, you will probably have found that keeping everyone&#8217;s database structure consistent can be a nightmare.</p>
<p>For example, say one of your colleagues adds a new feature, and in doing so, is required to add a new column to the database. They commit their code to Git and then push it to the repo. The next time you go to work on the project you pull the latest code down but you end up with a load of errors and a broken application because your database schema is now out of date.</p>
<p>Passing around a SQL dump is a horrible makeshift solution and it is totally inadequate for updating the production server because it causes downtime and things can go wrong due to human error.</p>
<p>Fortunately, Migrations are the answer to all of these problems.</p>
<h2>What are Migrations?</h2>
<p>Migrations are essentially a way to version control your database. Migrations are a series of timestamped instructions for making changes to your database. This allows you to record the changes you make to the schema so anyone else can simply run the instruction file to update their version of the database to keep things consistent. It also allows you to roll back any changes you have made to a database in the event that you made a mistake.</p>
<p>Even if you aren&#8217;t working with other developers, Migrations are really an essential part of building an application because it means you no longer have to write SQL or deal with a janky interface like phpMyAdmin. It also makes shipping live code much less stressful because you don&#8217;t have to worry about making changes to the live database.</p>
<p>If you have never used Migrations before, it can be kind of weird to think that you need them. But in all honesty, once you start using them, you will never go back.</p>
<h2>Using Migrations in Laravel 4</h2>
<p>Laravel 4 comes ready with Migrations out of the box. Using the <code>artisan</code> command line interface you can create new migrations just by running a single command.</p>
<p>However, in this tutorial we will be making our lives even easier by installing a fantastic package for Laravel Generators.</p>
<p>So here&#8217;s how to set up Migrations in Laravel 4.</p>
<h2>Setting up the database</h2>
<p>The first thing we need to do is to set up the database. Laravel provides you with a simple configuration file to save your database details, username and password.</p>
<p>Firstly, set up a new local database and create a new user. Next go to <code>app/config/database.php</code> and fill in your database details in the <code>connections</code> array.</p>
<pre class="brush: php; title: ; notranslate">
  'mysql' =&gt; array(
    'driver'    =&gt; 'mysql',
    'host'      =&gt; 'localhost',
    'database'  =&gt; 'cribbb',
    'username'  =&gt; 'cribbb',
    'password'  =&gt; '',
    'charset'   =&gt; 'utf8',
    'collation' =&gt; 'utf8_unicode_ci',
    'prefix'    =&gt; '',
  ),
</pre>
<p>Notice how easy it is to switch the type of database that you are using. All you would have to do is to change the <code>default</code> value.</p>
<h2>Installing Laravel 4 Generators</h2>
<p>Although Laravel 4 comes with Migrations out of the box, we can make them even easier by using the <a href="https://github.com/JeffreyWay/Laravel-4-Generators">Laravel 4 Generator</a> package by <a href="https://github.com/JeffreyWay">Jeffrey Way</a>.</p>
<p>First, open up your <code>composer.json</code> and add the Laravel 4 Generator package as a requirement:</p>
<pre class="brush: jscript; title: ; notranslate">
&quot;require&quot;: {
  &quot;laravel/framework&quot;: &quot;4.0.*&quot;,
  &quot;way/generators&quot;: &quot;dev-master&quot;
}
</pre>
<p>Next, update Composer from the Terminal:</p>
<pre class="brush: bash; title: ; notranslate">
$ composer update
</pre>
<p>Finally, go into <code>app/config/app.php</code> and add the following line at the end of the providers array:</p>
<pre class="brush: php; title: ; notranslate">
'Way\Generators\GeneratorsServiceProvider'
</pre>
<p>Now if you run <code>php artisan</code> from the command line you should see the new generator tasks.</p>
<h2>How do Migrations work?</h2>
<p>Migrations are basically just a set of timestamped instruction files that can be automatically run to modify a database. A migration file contains a class which have a series of SQL based methods for adding tables, updating columns or dropping a table all together.</p>
<p>In the migration file you will find an <code>up</code> method and a <code>down</code> method. This allows the migration file to make changes to a database, but also roll back those changes if it is required.</p>
<p>When a migration is run, it is recorded in a special <code>migrations</code> table in your database. This means Laravel knows which migrations have already run, and which are still needed to run to bring the database up to speed.</p>
<p>To create the <code>migrations</code> table, run the following command from Terminal:</p>
<pre class="brush: bash; title: ; notranslate">
$ php artisan migrate:install
</pre>
<p>If you now look in your database, you should see the new <code>migrations</code> table.</p>
<h2>Creating a Migration</h2>
<p><a href="http://cribbb.com">Cribbb</a> is going to be a social application so we need a table to store details of our users. In order to do that, we need to create a migration to create the <em>users</em> table.</p>
<p>To create the Migration, run the following line from the command line:</p>
<pre class="brush: bash; title: ; notranslate">
$ php artisan generate:migration create_users_table --fields=&quot;email:string, password:string&quot;
</pre>
<p>Now if you look under the <code>app/database/migrations</code> directory, you should see the new timestamped Migration file.</p>
<h2>The anatomy of a Migration</h2>
<p>When you run the Migration command above, Laravel will understand that you want to create a table called users. The fields option allows us to create fields for the table, in this case two fields called <em>email</em> and <em>password</em> which are both VARCHAR (which just means string).</p>
<p>Now if you look in the generated Migration file, you should have the following:</p>
<pre class="brush: php; title: ; notranslate">
class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('users', function(Blueprint $table) {
      $table-&gt;increments('id');
      $table-&gt;string('email');
      $table-&gt;string('password');
      $table-&gt;timestamps();
    });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::drop('users');
  }
}
</pre>
<p>Basically, all a Migration is, is a class with <code>up</code> and <code>down</code> methods. When the Migration is run, the instructions in the <code>up</code> method are run. When the Migration is rolled back, the instructions in the <code>down</code> method are run.</p>
<p>As you can see in this case, the <code>up</code> method creates the table and the default fields as well as the email and passwords fields that we specified from the command line. In the <code>down</code> method, the Migration will simply drop the table from the database.</p>
<p>If you run the migrate command now from the Terminal, Laravel will create the <code>users</code> table for you:</p>
<pre class="brush: bash; title: ; notranslate">
php artisan migrate
</pre>
<h2>Adding a column with a Migration</h2>
<p>If you want to add a column to a table using a Migration, you simply have to run a slightly different command to generate the right instructions.</p>
<p>For example, we also want our users to have a username.</p>
<p>To add this column, you would simply run this command in Terminal:</p>
<pre class="brush: bash; title: ; notranslate">
$ php artisan generate:migration add_username_to_users_table --fields=&quot;username:string&quot;
</pre>
<p>Notice how it is <code>add</code> instead of <code>create</code>? This will create the following Migration file.</p>
<pre class="brush: php; title: ; notranslate">
class AddUsernameToUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::table('users', function(Blueprint $table) {
      $table-&gt;string('username');
    });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
   public function down()
   {
     Schema::table('users', function(Blueprint $table) {
       $table-&gt;dropColumn('username');
   });
 }
}
</pre>
<p>Again, run the <code>migrate</code> command from Terminal to add the username column to the users table.</p>
<pre class="brush: bash; title: ; notranslate">
$ php artisan migrate
</pre>
<h2>Read more about Laravel Migrations</h2>
<p>See, how easy was that? Now that you have simple version control for your database, other developers can easily get started working on your project and rolling out changes to the server will be a breeze.</p>
<p>To read more about Laravel Migrations, take a look at the following articles as well as as the <a href="http://four.laravel.com/docs/migrations">Laravel 4 documentation</a>.</p>
<ul>
<li><a href="http://codehappy.daylerees.com/migrations">Code Happy &#8211; Migrations</a></li>
<li><a href="http://laravelbook.com/laravel-migrations-managing-databases/">Managing Databases with Migrations</a></li>
</ul>
<p>This tutorial is the second in a series of posts showing you how to build an entire web application from scratch. All of the tutorials will be free to web and you see all of the code up on <a href="https://github.com/philipbrown/cribbb">GitHub</a>.</p>
<p>Last week I covered <a href="http://culttt.com/2013/04/29/getting-started-with-laravel-4/">getting started with Laravel 4</a>.</p>
<p>Follow us on <a href="http://twitter.com/culttt">Twitter</a>, <a href="http://facebook.com">Facebook</a> or <a href="https://plus.google.com/105545788844824874492/posts">Google Plus</a> to make sure you never miss a post!</p>
<p><a href="http://culttt.com/2013/05/06/laravel-4-migrations/">Laravel 4 Migrations</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/05/06/laravel-4-migrations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Laravel 4</title>
		<link>http://culttt.com/2013/04/29/getting-started-with-laravel-4/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-laravel-4</link>
		<comments>http://culttt.com/2013/04/29/getting-started-with-laravel-4/#comments</comments>
		<pubDate>Mon, 29 Apr 2013 07:25:23 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Cribbb]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=3043</guid>
		<description><![CDATA[<p>Laravel 4 is the upcoming latest release of the popular PHP framework Laravel. Laravel is a &#8220;clean and classy&#8221; modern PHP framework for building web applications. Heavily inspired by the likes of Ruby on Rails, as well as other modern PHP frameworks like Symfony, Laravel 4 aims to show how far PHP has matured over [...]</p><p><a href="http://culttt.com/2013/04/29/getting-started-with-laravel-4/">Getting started with Laravel 4</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/04/Getting-started-with-Laravel-4.jpg" alt="Getting started with Laravel 4" /><br />
<a href="https://github.com/laravel/framework">Laravel 4</a> is the upcoming latest release of the popular PHP framework <a href="http://laravel.com">Laravel</a>. Laravel is a <em>&#8220;clean and classy&#8221;</em> modern PHP framework for building web applications. Heavily inspired by the likes of <a href="http://rubyonrails.org/">Ruby on Rails</a>, as well as other modern PHP frameworks like <a href="http://symfony.com/">Symfony</a>, Laravel 4 aims to show how far PHP has matured over the last couple of years by allowing you to write great web applications from scratch.</p>
<p>Laravel 4 builds upon the hugely successful <a href="http://laravel.com">Laravel 3 framework</a>, but has taken some dramatic steps forward since the last release. Laravel 4 is now a much more testable framework, whilst still maintaining it&#8217;s clean and clear syntax as well as adding a wide array of new components and features.</p>
<p>Laravel 4 leverages <a href="http://getcomposer.org/">Composer</a> to manage updates and to decouple the framework into individual components. You are now much more free to mix and match components from the PHP community. Laravel 4 itself uses some of the most popular components from the Symfony framework, amongst others, so that it does not have to reinvent the wheel.</p>
<p>All of these reasons make Laravel 4 the perfect choice of PHP framework for your next project.</p>
<p>Laravel 4 has not been officially released yet, although the final version release is imminent. However, you can still get started with the framework today.</p>
<p>In this tutorial I&#8217;m going to show you everything you need to get started with Laravel 4.</p>
<p>This is actually the second time that I have written this tutorial. The first time I was just explaining the process for setting up Laravel 4 that loosely followed the <a href="http://four.laravel.com">documentation</a>. However, after reading <a href="http://fideloper.com/best-way-to-install-laravel4">this</a> great tutorial by <a href="https://twitter.com/fideloper">Chris Fidao</a>, I decided to rewrite my guide but follow the slightly different method provided by <a href="https://twitter.com/akuzemchak">Aaron Kuzemchak</a> <a href="https://gist.github.com/akuzemchak/5210425">here</a>. So kudos to those two, you learn something new everyday. The majority of this post will be standing on the shoulder of giants, but hopefully I can expand on some of the nuances in getting started with Laravel 4.</p>
<h2>Requirements</h2>
<p>Laravel 4 pretty much needs no configuration out of the box. However, there are a couple of requirements you will need on your local machine.</p>
<p>Firstly you will need to install <a href="http://getcomposer.org/">Composer</a>. Composer is a handy package manager for PHP that allows you to update and manage the different components of your project. If you haven&#8217;t already got Composer set up, take a look at my tutorial, <a href="http://culttt.com/2013/01/07/what-is-php-composer/">What is PHP composer?</a>.</p>
<p>You will also need to be running <code>PHP >= 5.3.7</code> and you need the <code>MCrypt PHP Extension</code> to be installed. I will be using PHP 5.4+. I&#8217;m using OS X, and so the rest of this tutorial will reference that operating system. I&#8217;ll assume that you are already have your environment set up, because it&#8217;s outside the scope of this tutorial.</p>
<p>And finally, you will of course need to have Git installed. If you are new to Git, take a look at my overview, <a href="http://culttt.com/2012/10/10/why-you-need-to-start-using-git-today/">Why you need to start using Git today</a>.</p>
<h2>Installing Laravel 4</h2>
<p>So the first thing we need to do is to clone the Laravel repository from GitHub. As I mentioned at the top of this post, Laravel 4 hasn&#8217;t officially been released yet, but we can start using it today by cloning the <code>develop</code> branch.</p>
<pre class="brush: bash; title: ; notranslate">
$ git clone -o laravel -b develop https://github.com/laravel/laravel.git cribbb
</pre>
<p>Here I&#8217;m using the <code>git clone</code> command to get the latest copy of the framework and save it into the directory named <code>cribbb</code>.</p>
<p><code>-o laravel</code> means the remote branch will be named <em>laravel</em> instead of the default of <em>origin</em>. This is so we can pull in changes to the framework, but still maintain our own <code>origin</code>.</p>
<p><code>-b develop</code> means we want the <code>develop</code> branch.</p>
<p>To read more about the <code>git clone</code> command, take a look at the <a href="http://git-scm.com/docs/git-clone">documentation</a>.</p>
<p>Once the Laravel repo has been cloned, move into the project directory:</p>
<pre class="brush: bash; title: ; notranslate">
cd cribbb
</pre>
<p>Next we need to create our own Master branch so this project starts at the beginning of it&#8217;s own timeline. To do this, run the following command.</p>
<pre class="brush: bash; title: ; notranslate">
git checkout --orphan master
</pre>
<p>This basically creates a new branch with a new timeline with no parent branches and calls it Master.</p>
<p>Again, to read more about this specific command and the options, take a look at the in-depth <a href="http://git-scm.com/docs/git-checkout">documentation</a>.</p>
<p>Now we need to commit the changes.</p>
<p>Run the following command to see all the new framework files that have not been committed to our repo yet:</p>
<pre class="brush: bash; title: ; notranslate">
git status
</pre>
<p>Next, commit all the files with a message:</p>
<pre class="brush: bash; title: ; notranslate">
git commit -m &quot;Initial commit&quot;
</pre>
<p>Now when you want to update Laravel, you can run:</p>
<pre class="brush: bash; title: ; notranslate">
git fetch laravel
</pre>
<p><code>git fetch</code> will download updates from the <code>laraval</code> repository (<a href="http://git-scm.com/docs/git-fetch">documentation</a>).</p>
<p>And to merge updates, you would run the following command:</p>
<pre class="brush: bash; title: ; notranslate">
git merge --squash -m &quot;Upgrade Laravel&quot; laravel/develop
</pre>
<p>This will merge the updates as one commit (<a href="http://git-scm.com/docs/git-merge">documentation</a>).</p>
<p>Now you can run <code>composer update</code> to update any composer registered libraries (note I&#8217;m running <code>composer.phar</code> globally from my <code>usr/local/bin</code> directory).</p>
<pre class="brush: bash; title: ; notranslate">
composer update
</pre>
<p>Now that you have this set up, whenever a component is updated you can just run <code>composer update</code> to get the latest updates without having to mess with updating files within directories.</p>
<p>And finally, set your own <code>origin</code> by running the following command with your own git repo url.</p>
<pre class="brush: bash; title: ; notranslate">
git remote add origin git@github.com:philipbrown/cribbb.git
</pre>
<h2>Configuring Laravel</h2>
<p>The only configuration option that we need to set up now is to create the encryption key that is used within the framework. To do this, all we need to do is to run:</p>
<pre class="brush: bash; title: ; notranslate">
php artisan key:generate
</pre>
<h2>Running Laravel</h2>
<p>Now that we have Laravel installed, it&#8217;s all ready to run. If you are using PHP 5.4, you can run the following command from Terminal to quickly start up the server without having to create a new Virtual Host.</p>
<pre class="brush: bash; title: ; notranslate">
$ php artisan serve
</pre>
<p>Now if you visit <a href="http://localhost:8000">http://localhost:8000</a> in your browser you should see the <em>Hello World!</em> front page.</p>
<p>If you aren&#8217;t using PHP 5.4, you will just need to create a new VirtualHost and point it to the <code>/public</code> directory of your project.</p>
<p>Now is a good time to commit your work to Git.</p>
<pre class="brush: bash; title: ; notranslate">
$ git add -A
$ commit -m &quot;Yay&quot;
</pre>
<p>Congratulations! You have just set up Laravel 4!</p>
<h2>About this series</h2>
<p>This is the first of a huge series on creating a web application from scratch. Over the course of many future weeks, I&#8217;m going to show you how to create a web application and everything that goes into it.</p>
<p>The application I&#8217;m going to create is going to be called <a href="http://cribbb.com">Cribbb</a>. I haven&#8217;t fully decided what it&#8217;s going to be yet, so I&#8217;m just letting the project find it&#8217;s own direction.</p>
<p>I&#8217;m going to be (obviously) using Laravel for all of the server side stuff and we&#8217;ll create a <a href="http://culttt.com/2013/04/15/what-are-restful-web-services/">RESTful API</a>.</p>
<p>I&#8217;m going to use <a href="http://emberjs.com/">Ember.js</a> for all of the client side stuff and we&#8217;ll be using <a href="http://culttt.com/2013/01/14/getting-started-with-sass/">Sass</a> and a lot more cool new front end stuff that you might not have used in a project before.</p>
<p>Hopefully this will be a good guide for going from an idea to a fully working web application as well as practical tutorials in getting started with some of the latest technology for building online products.</p>
<p>And all these tutorials will be free to web and all of the code will be open sourced on <a href="https://github.com/philipbrown/cribbb">GitHub</a>.</p>
<p>So if you have an idea for an online application, but you don&#8217;t know where to get started, follow along with this tutorial series as I show you everything you will need to do to create a modern web application.</p>
<p>Remember to follow Culttt on <a href="http://twitter.com/culttt">Twitter</a>, <a href="http://facebook.com/culttt">Facebook</a> or <a href="https://plus.google.com/105545788844824874492/posts">Google Plus</a> to make sure you never miss a tutorial!</p>
<p>See you next Monday!</p>
<p><a href="http://culttt.com/2013/04/29/getting-started-with-laravel-4/">Getting started with Laravel 4</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/04/29/getting-started-with-laravel-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What are RESTful Web Services?</title>
		<link>http://culttt.com/2013/04/15/what-are-restful-web-services/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-are-restful-web-services</link>
		<comments>http://culttt.com/2013/04/15/what-are-restful-web-services/#comments</comments>
		<pubDate>Mon, 15 Apr 2013 07:25:43 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2993</guid>
		<description><![CDATA[<p>&#8220;REST&#8221; is a common word in the world of web applications and services. REST usually refers to the transfer of data between servers and clients. For example, if you wanted to get updates from Twitter, you would be using Twitter&#8217;s REST API. In this post I hope to explain exactly what REST means, how you [...]</p><p><a href="http://culttt.com/2013/04/15/what-are-restful-web-services/">What are RESTful Web Services?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/04/What-are-RESTful-Web-Services.jpg" alt="What are RESTful Web Services" /><br />
&#8220;REST&#8221; is a common word in the world of web applications and services. REST usually refers to the transfer of data between servers and clients. For example, if you wanted to get updates from Twitter, you would be using Twitter&#8217;s <em>REST API</em>.</p>
<p>In this post I hope to explain exactly what REST means, how you can use it to get data from web services and how you can build your web applications to take advantage of <em>RESTful</em> architecture.</p>
<h2>What is REST?</h2>
<p><a href="http://en.wikipedia.org/wiki/Representational_state_transfer">Representational State Transfer (REST)</a> is a type of distributed software architecture that is predominately used on the Internet. REST basically controls how data is sent to and from servers and clients and acts as a set of rules that govern this type of data transfer.</p>
<p>REST follows many of the same conventions as <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">Hypertext Transfer Protocol (HTTP)</a>, making it easy to pick up and understand.</p>
<p>When using REST, you will usually want to do one of the following four actions:</p>
<ul>
<li>Create (POST)</li>
<li>Retrieve (GET)</li>
<li>Update (PUT)</li>
<li>Delete (DELETE)</li>
</ul>
<p>POST, GET, PUT and DELETE are HTTP request methods. By making each of the methods represented by a verb, the methods are easy to understand and remember.</p>
<p>This all might seem complicated, but you&#8217;ve already been using all of these methods whilst browsing the web. The two most common and visible HTTP methods are POST and GET.</p>
<p>When you submit data through a form on a website, you are making a <b>POST</b> request. A POST request is simply a message to the server that has the submitted data within the body.</p>
<p>It&#8217;s easy to spot a <b>GET</b> request because it is often visible in the URL of the website. For example, <em>http://www.youtube.com/watch?v=9bZkp7q19f0</em> is using a GET request. In this example, your browser is using a GET request to get the video that is represented by <b>9bZkp7q19f0</b>.</p>
<h2>REST URIs</h2>
<p>An important part of RESTful architecture is the URIs that are used to transfer data. REST URIs are structured to ensure that they are intuitively understandable and obvious as to their purpose.</p>
<p>For example, to get all the users of a particular service, the REST URI would usually look like this:</p>
<p><em>domain.com/users</em></p>
<p>This would return all of the users of the system.</p>
<p>To get the details of a particular user, the REST URI could be:</p>
<p><em>domain.com/users/1</em></p>
<p>As you can see, the purpose of these URIs is extremely obvious and follows in the intuitive nature of RESTful architecture.</p>
<h2>JSON, XML or both</h2>
<p>When you make a REST request, you are returned a representation of the data from the server. The data you are returned is not the actual database, but rather data in a format such as XML, JSON or both.</p>
<p><em>XML</em> (Extensible Markup Language) is a markup language that is used to store and transfer data. <em>JSON</em> (Javascript Object Notation), despite it&#8217;s name, is a language agnostic method for serialising and transferring data.</p>
<p>When transferring data you can use either XML or JSON. Often web services will offer both formats. There are many differences between the two formats and so it&#8217;s hard to say whether one is better than the other. XML is a markup language and is used for transferring different types with great flexibility. JSON is generally lighter than XML and so the same amount of data can be transferred with less bandwidth. JSON also fits nicely with Javascript heavy web applications.</p>
<p>The choice between XML or JSON really comes down to your application. Whilst JSON is perfect for lightweight data transfer in web applications, it does have restrictions and constraints that XML does not.</p>
<h2>REST Vs SOAP</h2>
<p><em>SOAP (Simple Object Access Protocol)</em> is a protocol for transferring data across networks. SOAP relies on XML and is generally considered much more complicated than REST.</p>
<p>REST is simpler than SOAP because it is based on GET, POST, PUT and DELETE. SOAP on the other hand has it&#8217;s own methods for accomplishing the same things. This means you inherently already know how to use REST, whereas SOAP requires a level of learning.</p>
<p>REST is also generally considered better than SOAP because it allows for JSON. As I mentioned earlier, this is particularly important for consumer web services that rely on Javascript heavy web applications and require a much simpler and lighter method for data transfer.</p>
<p>SOAP is older than REST and comes burdened with specifications for it&#8217;s use. REST has no specifications and so once again, it makes it easier to use.</p>
<p>SOAP does have some specific advantages over REST. For example, REST only allows for SSL as a method for security, whereas SOAP has security features like <a href="http://en.wikipedia.org/wiki/WS-Security">WS-Security</a>, although you wouldn&#8217;t need it for the average application.</p>
<p>REST is seen as the future of web applications because it is hard to find a case where SOAP is actually a better choice. REST is easier, simpler and has become the chosen method for companies like Google Facebook and Twitter. REST forms an integral part of <a href="http://rubyonrails.org/">Ruby on Rails</a> and allows for easy integration with Ajax heavy asynchronous applications.</p>
<h2>Conclusion</h2>
<p>So to conclude, REST is a type of data transfer that is built upon the architecture of the HTTP protocol. It allows you to easily send and retrieve data between two different services using XML or JSON.</p>
<p>When structuring your web applications, it&#8217;s usually good practice to build them using RESTful architecture. This means that collections and resources are easily recognised and can form the basis of building a RESTful API.</p>
<p>When you build an application that requires a Javascript heavy front-end, or integration with a smartphone application, using a RESTful architecture becomes a necessity because it allows you to transfer data from the API to the client. It&#8217;s often good practice to plan out your RESTful collections and resources at the very outset.</p>
<p>So the next time you start a web application project, think about how you can make it more RESTful. It will probably not only make your application&#8217;s architecture better, but it will also allow you to easily build an API in the future to integrate with other services or applications.</p>
<p><a href="http://culttt.com/2013/04/15/what-are-restful-web-services/">What are RESTful Web Services?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/04/15/what-are-restful-web-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to deploy WordPress themes with Git</title>
		<link>http://culttt.com/2013/04/08/how-to-deploy-wordpress-themes-with-git/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-deploy-wordpress-themes-with-git</link>
		<comments>http://culttt.com/2013/04/08/how-to-deploy-wordpress-themes-with-git/#comments</comments>
		<pubDate>Mon, 08 Apr 2013 07:25:07 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2966</guid>
		<description><![CDATA[<p>One of the legacy problems with WordPress is it does not offer an easy out of the box solution for using Git. This means that it is often the case that theme management is handled through FTP. Using Git for deployment is far superior than FTP in just about every way. In this post I [...]</p><p><a href="http://culttt.com/2013/04/08/how-to-deploy-wordpress-themes-with-git/">How to deploy WordPress themes with Git</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/04/How-to-deploy-WordPress-themes-with-Git.jpg" alt="How to deploy WordPress themes with Git" /><br />
One of the legacy problems with WordPress is it does not offer an easy out of the box solution for using Git. This means that it is often the case that theme management is handled through FTP.</p>
<p>Using Git for deployment is far superior than FTP in just about every way. In this post I will show you why you should only ever deploy with Git, and how easy it is to set it up.</p>
<h2>Why you should use Git?</h2>
<p>I&#8217;ve already covered <a href="http://culttt.com/2012/10/10/why-you-need-to-start-using-git-today/">why you should use Git</a> in the past, so I will keep this to a brief summary.</p>
<p>Git is a version control system that sits discretely in the background of your project and monitors any changes you make. After you make a change to your code you can commit your changes to Git which makes a new entry in your project&#8217;s timeline. This gives you the ability to go back in time and resurrect your code as it was at a certain point in time.</p>
<p>Git is also invaluable when you are working as part of a team of developers or when you are working on a project that has many concurrent development features or versions.</p>
<p>One of the big advantages of using Git is when it comes to deployment. As you probably already know, using FTP for deployment is not very good. FTP requires you to drag and drop files into their correct folders on the server. This means if you need to update a website that has files that are changed in many different folders, it becomes quite difficult. You also face the risk that an unsuspecting user will load a page that breaks because you haven&#8217;t finished uploading all of the new files.</p>
<p>Git allows you to manage deployment from the command line. This means you can push a new update and all of the files that are changed are instantly updated at the same time.</p>
<p>It also means that should you push a new update that critically breaks your website, it is really easy to rollback to the previous version. This would be almost impossible using regular old FTP.</p>
<p>So hopefully you can see the many advantages of Git when it comes to deployment. Again, Git will improve your workflow in a number of different areas which you can <a href="http://culttt.com/2012/10/10/why-you-need-to-start-using-git-today/">read more</a> about.</p>
<h2>How does Git deployment work with WordPress</h2>
<p>There are many different ways you can handle Git deployment using WordPress. Personally, I only use Git for theme deployment, rather than having it manage my entire WordPress installation. This is because I don&#8217;t trust open source plugins enough to compromise my deployment. For example say a plugin makes a change to a file on the live server. The next time I push a deployment my files will overwrite this change.</p>
<p>If you do want Git to manage your entire installation, that&#8217;s fine. This is a good set up because you can update plugins locally to ensure nothing breaks before it ever hits the live server.</p>
<p>So the overview of how my Git deployment works is:</p>
<h3>1. Local repository</h3>
<p>Firstly I have my WordPress installation set up locally so I can develop themes and make changes without affecting the live site. Making changes to a live site is a really bad habit that you need to get out of. I have my Git repository set up in <code>/wp-content/themes/my-theme</code> so only the changes to my theme get managed.</p>
<h3>2. Git repository on the server</h3>
<p>Next I have a bare repository set up on my server. I like to keep all my repositories under <code>/var/git</code>, but you can keep them wherever you want really.</p>
<h3>3. Live site files</h3>
<p>And finally, I have my live site WordPress installation under <code>/var/www/path-to-live-site</code> as you typically would with any Linux set up.</p>
<p>So the workflow of making changes is:</p>
<p><em>Local changes</em><br />
Firstly we make local changes and commit them to Git</p>
<p><em>Push to the server</em><br />
Next we push the changes to the Git repository on the server</p>
<p><em>Automatically update</em><br />
When new commits are added to the Git repository, it will automatically update the live theme.</p>
<p>It&#8217;s that simple. Easy integration with Git and no more FTP.</p>
<p>Let&#8217;s set everything up.</p>
<h2>Setting up Git and WordPress</h2>
<p>So as I&#8217;ve outlined above, there are three main stages to setting up Git to work with WordPress:</p>
<h3>Local repository</h3>
<p>So the first thing to do locally is simply create a new Git repository. I&#8217;m going to assume that you already have Git set up on your machine.</p>
<p>To create a new repository, go to the root of your theme and run:</p>
<pre class="brush: bash; title: ; notranslate">
$ cd wp-content/theme/my-theme
$ git init
</pre>
<p>This will create a new repository.</p>
<p>Next we need to add all the current files to the repository.</p>
<pre class="brush: bash; title: ; notranslate">
// Shows all unstaged files
$ git status

// Adds all files to the current commit
$ git add -A

// Commits the files with a message
$ git commit -m &quot;Add all the things&quot;
</pre>
<p>Now if you run <code>git status</code> again, there should be nothing left to commit.</p>
<h3>Server repository</h3>
<p>Next we need to create the server repository. SSH into your server and into the directory where you want to store your Git repositories.</p>
<p>All we have to do at this stage is to create a bare repository. Run the following command in your directory.</p>
<pre class="brush: bash; title: ; notranslate">
$ git init --bare
</pre>
<p>A bare repository is essentially the same as the local repository you just made but it doesn&#8217;t have a working tree. You should use bare repositories to push and pull from on a centralised server because it doesn&#8217;t have the complications of a working tree.</p>
<p>Now that we have a repository to push to on the server, we can add an origin to our local repository.</p>
<p>Go back to your local repository and run the following command, substituting your SSH login, server IP and path to the bare git repository you just made:</p>
<pre class="brush: bash; title: ; notranslate">
$ git remote add origin name@123.456.789:path/to/your/git
</pre>
<p>You should be required to enter your server password.</p>
<p><em>Origin</em> is simply the main centralised repository. Even though all of your work originated from your local machine, the bare repository is still called the origin. This means that should you ever want to allow access to another developer, all they have to do is pull from the origin.</p>
<p>Next you can run the following command to push your code from your local machine to the server:</p>
<pre class="brush: bash; title: ; notranslate">
$ git push origin master
</pre>
<p>This is simply saying, push the master branch of the current repository to the origin.</p>
<p>Now if you have a look at the <code>git log</code> of the server&#8217;s repository, you should see that your code has been pushed up. Because this is a bare repository without a working tree, your code won&#8217;t actually be in the repository.</p>
<h3>Automatic update</h3>
<p>If you look at your live installation directory, you will notice nothing has changed. In order to automatically update the live files we need to set up a post update hook. This is simply a job that will be run whenever the git repository is updated.</p>
<p>Go into your bare repository, then into the <code>hooks</code> directory.</p>
<pre class="brush: bash; title: ; notranslate">
$ cd hooks
</pre>
<p>If you list all of the files in this directory you will see a set of sample files that you can use to create your hook.</p>
<pre class="brush: bash; title: ; notranslate">
$ ls -l
</pre>
<p>To create a post-update hook, simply create a new file and copy the following:</p>
<pre class="brush: bash; title: ; notranslate">
// Create a new file
$ sudo vim post-update

// Copy this text
#!/bin/sh
export GIT_WORK_TREE=/path/to/you/live/files
git checkout -f
</pre>
<p>This will checkout your files into the directory your have specified every time the repository is updated.</p>
<p>Now if you go back to your local code, make a change, commit the change and push it to the origin you will see your code magically update. You can now deploy changes to your live site without ever having to touch FTP again.</p>
<h2>Conclusion</h2>
<p>And there you have it, simple Git deployment using WordPress. There are many ways you extend this. For example, you could deploy to a development version or staging version depending on which branch that you push to the origin. This would allow you to test your changes on the server before you deploy the code to the live site.</p>
<p>Hopefully that was a nice and easy introduction to using Git with WordPress. You can of course use the same technique for deployment of any website. I promise you, once you get away from using FTP, you will never look back.</p>
<p><a href="http://culttt.com/2013/04/08/how-to-deploy-wordpress-themes-with-git/">How to deploy WordPress themes with Git</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/04/08/how-to-deploy-wordpress-themes-with-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is Dependancy Injection?</title>
		<link>http://culttt.com/2013/04/01/what-is-dependancy-injection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-is-dependancy-injection</link>
		<comments>http://culttt.com/2013/04/01/what-is-dependancy-injection/#comments</comments>
		<pubDate>Mon, 01 Apr 2013 07:20:15 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2935</guid>
		<description><![CDATA[<p>When you start to build complex web applications, it&#8217;s important to structure your components so that they remain independent and your architecture remains flexible and maintainable going forward. However, once you add even the slightest bit of complexity, it can become difficult to maintain this form. In Object Orientated Programming, it is inevitable that one [...]</p><p><a href="http://culttt.com/2013/04/01/what-is-dependancy-injection/">What is Dependancy Injection?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/03/What-is-Dependancy-Injection.jpg" alt="What is Dependancy Injection" /><br />
When you start to build complex web applications, it&#8217;s important to structure your components so that they remain independent and your architecture remains flexible and maintainable going forward. However, once you add even the slightest bit of complexity, it can become difficult to maintain this form.</p>
<p>In Object Orientated Programming, it is inevitable that one object will need to use an instance of another. This is likely going to be happening in places all over your project. Say for example you are using a MySQL database. When you are making calls to the database, you will be using an instance of the database object. But what happens if you need to switch databases to use PostgreSQL instead? Dependancy Injection is a design pattern that allows you to &#8220;decouple&#8221; these two components so they remain independent.</p>
<p>A second big advantage to Dependancy Injection is when it comes to testing. Recently I introduced <a href="http://culttt.com/2013/03/11/what-is-test-driven-development/">Test Driven Development</a> and then we explored <a href="http://culttt.com/2013/03/13/getting-started-with-phpunit/">PHPUnit</a>. Dependancy Injection is another important part of writing good, well tested software.</p>
<p>Back to our database example. When you are testing your code, you probably don&#8217;t want to have to actually connect to a Database. Connecting to a database during testing can slow the process down and it requires you to maintain test data when really all you need to test are the methods that interact with the database. By using Dependancy Injection, you can replace the  database object with a static resource that acts the way you would expect the database to act.</p>
<p>So as you can see, Dependancy Injection allows to keep your components independent. Dependancy Injection sounds like such a complicated idea, but really it&#8217;s very simple. Essentially it just breaks down to passing an object it&#8217;s dependancies, rather than letting it create them itself.</p>
<h2>An example of Dependancy Injection</h2>
<p>To show you how Dependancy Injection works in real life, here is an example in code. As usual, these examples are in PHP, but hopefully it should be easy enough to translate into whatever language you are using. Don&#8217;t take this code too literally, it&#8217;s just an example of passing a dependancy, rather than something you would actually want to use.</p>
<h3>What not to do</h3>
<p>Imagine we have the following database class:</p>
<pre class="brush: php; title: ; notranslate">
class Database {
  public function __construct(
    $dsn,
    $user,
    $password
  ){
    // Make a connection to the database
  }
}
</pre>
<p>And we have a User class that creates a new user:</p>
<pre class="brush: php; title: ; notranslate">
class User {
  private $name;
  private $age;
  private $website;
  private $db;

  public function __construct(
    $name,
    $age,
    $website
  ){
    $this-&gt;name = $name;
    $this-&gt;age = $age;
    $this-&gt;website = $website;
    // Instantiate database
    $this-&gt;db = new Database(&quot;
      mysql:host=localhost;dbname=database&quot;,
      &quot;username&quot;,
      &quot;password&quot;
    );
  }
}
</pre>
<p>This code is bad for 3 main reasons.</p>
<ol>
<li><b>Multiple concerns</b><br />
A class should only ever have one concern. In our User class, we have to deal with the database when really it has nothing to do with the user.</li>
<li><b>Making changes is difficult</b><br />
Imagine if you had to change the database type or the username or password in every place where you are using this database connection. As you can probably tell, having your classes too closely coupled like this will make it a nightmare to maintain the codebase in the future.</li>
<li><b>Unit testing is difficult</b><br />
Unit testing is also much more difficult because now we have to deal with the database. As I mentioned above, during testing, you only want to be testing one specific thing. With the Database class being created in the User class, it means we can&#8217;t switch it out for testing purposes.</li>
</ol>
<h3>The correct way to use Dependancy Injection</h3>
<p>Hopefully that example above shows the pain of not using Dependancy Injection.</p>
<p>To refactor this example to use Dependancy Injection, we simply have to pass the database object to the User class constructor:</p>
<pre class="brush: php; title: ; notranslate">
class User {
  private $name;
  private $age;
  private $website;
  private $db

  public function __construct(
    $name,
    $age,
    $website,
    Database $database
  ){
    $this-&gt;name = $name;
    $this-&gt;age = $age;
    $this-&gt;website = $website;
    $this-&gt;db = $database;
  }
}
</pre>
<p>Now that we are passing an instance of the database to the User class on construction we have solved the three problems that we had before.</p>
<ol>
<li><b>Single concern</b><br />
The User class is now only concerned with the User as it no longer needs to care about the database.</li>
<li><b>No more repetition</b><br />
Now that we have cut out all the duplicate code it is now much easier to make a change to the database parameters because we only have to do it once. The User class never needs to care about changes made to the database.</li>
<li><b>Easier to test</b><br />
Now that the User class is just given an instance of the database it makes this much easier to test. Now we can just pass an object that provides the same api as the database, but without having to actually make a connection or return real results.</li>
</ol>
<h2>Conclusion</h2>
<p>Whilst Dependancy Injection can seem like a difficult term to get your head around, it is really very simple. Dependancy Injection is basically just providing an object with the things it needs, rather than allowing it to create them itself. So if an object requires access to the database, instead of allowing the object to create an instance of the database class, we can provide an instance instead.</p>
<p>Dependancy Injection is really very important when it comes to testing. When you provide an object with it&#8217;s dependancies, it makes it very easy to mock them. If you allow an object to create it&#8217;s own dependancies, you now need to deal with them during your tests as the object now has multiple concerns.</p>
<p>To find out more about Dependancy Injection, have a read of <a href="http://fabien.potencier.org/article/11/what-is-dependency-injection">this</a> article by Fabien Pontencier and <a href="http://www.martinfowler.com/articles/injection.html">this</a> article by Martin Fowler</a>.</p>
<p><a href="http://culttt.com/2013/04/01/what-is-dependancy-injection/">What is Dependancy Injection?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/04/01/what-is-dependancy-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What are PHP Lambdas and Closures?</title>
		<link>http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-are-php-lambdas-and-closures</link>
		<comments>http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/#comments</comments>
		<pubDate>Mon, 25 Mar 2013 08:25:39 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2911</guid>
		<description><![CDATA[<p>Lambdas and Closures are relatively new additions to PHP after shipping with version 5.3. Both offer some new functionality and the ability to refactor old code to be cleaner and more intuitive. However, I think many developers are unaware of Lambdas and Closures or confused about what they actually do. In this post I will [...]</p><p><a href="http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/">What are PHP Lambdas and Closures?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/03/What-are-PHP-Lambdas-and-Closures.jpg" alt="What are PHP Lambdas and Closures" /><br />
Lambdas and Closures are relatively new additions to PHP after shipping with version 5.3. Both offer some new functionality and the ability to refactor old code to be cleaner and more intuitive. However, I think many developers are unaware of Lambdas and Closures or confused about what they actually do.</p>
<p>In this post I will be explaining Lambdas and Closures, give you some example code to show their usage and give you a real life example of them in action to show you their prevalence in modern PHP.</p>
<h2>What is a Lambda?</h2>
<p>A Lambda is an anonymous function that is can be assigned to a variable or passed to another function as an argument. If you are familiar with other programming languages like Javascript or Ruby, you will be very familiar with anonymous functions. </p>
<h3>Anonymous functions</h3>
<p>An anonymous function is simply a function with no name.</p>
<p>For example, to create a regular function, you might write something like this:</p>
<pre class="brush: php; title: ; notranslate">
// Regular function
function greeting () {
	return &quot;Hello world&quot;;
}
</pre>
<p>You can then simply call this function like this:</p>
<pre class="brush: php; title: ; notranslate">
echo greeting();
// Returns &quot;Hello world&quot;
</pre>
<p>An anonymous function has no name so you would define it like this:</p>
<pre class="brush: php; title: ; notranslate">
// Anonymous function
function () {
	return &quot;Hello world&quot;;
}
</pre>
<h3>Using Lambdas</h3>
<p>Because the function has no name, you can&#8217;t call it like a regular function. Instead you must either assign it to a variable or pass it to another function as an argument.</p>
<pre class="brush: php; title: ; notranslate">
// Anonymous function
// assigned to variable
$greeting = function () {
  return &quot;Hello world&quot;;
}

// Call function
echo $greeting();
// Returns &quot;Hello world&quot;
</pre>
<p>To so use the anonymous function, we assign it to a variable and then call that variable as a function.</p>
<p>You could also pass the function to another function, like this:</p>
<pre class="brush: php; title: ; notranslate">
// Pass Lambda to function
function shout ($message){
	$message();
}

// Call function
shout(function(){
	return &quot;Hello world&quot;;
});
</pre>
<h3>Why would you want to use a Lambda?</h3>
<p>Lambdas are useful because they are throw away functions that you can use once. Often, you will need a function to do a job, but it doesn&#8217;t make sense to have it within the global scope or to even make it available as part of your code. Instead of having a function used once and then left lying around, you can use a Lambda instead.</p>
<p>Of course, you have been able to use the create_function function in PHP for a while now. This basically does the same job.</p>
<pre class="brush: php; title: ; notranslate">
// Use create_function
$greeting = create_function(
	echo &quot;Hello world&quot;;
);

// Call function
$greeting();
</pre>
<h2>What is a Closure?</h2>
<p>A Closure is essentially the same as a Lambda apart from it can access variables outside the scope that it was created.</p>
<p>For example:</p>
<pre class="brush: php; title: ; notranslate">
// Create a user
$user = &quot;Philip&quot;;

// Create a Closure
$greeting = function() use ($user) {
  echo &quot;Hello $user&quot;;
};

// Greet the user
$greeting(); // Returns &quot;Hello Philip&quot;
</pre>
<p>As you can see above, the Closure is able to access the $user variable. because it was declared in the use clause of the Closure function definition.</p>
<p>If you were to alter the $user variable within the Closure, it would not effect the original variable. To update the original variable, we can append an ampersand. An ampersand before a variable means this is a reference and so the original variable is also updated.</p>
<p>For example:</p>
<pre class="brush: php; title: ; notranslate">
// Set counter
$i = 0;
// Increase counter within the scope
// of the function
$closure = function () use ($i){ $i++; };
// Run the function
$closure();
// The global count hasn't changed
echo $i; // Returns 0

// Reset count
$i = 0;
// Increase counter within the scope
// of the function but pass it as a reference
$closure = function () use (&amp;$i){ $i++; };
// Run the function
$closure();
// The global count has increased
echo $i; // Returns 1
</pre>
<p>Closures are also useful when using PHP functions that accept a callback function like array_map, array_filter, array_reduce or array_walk.</p>
<p>The array_walk function takes an array and runs it through the callback function.</p>
<pre class="brush: php; title: ; notranslate">
// An array of names
$users = array(&quot;John&quot;, &quot;Jane&quot;, &quot;Sally&quot;, &quot;Philip&quot;);

// Pass the array to array_walk
array_walk($users, function ($name) {
	echo &quot;Hello $name&lt;br&gt;&quot;;
});
// Returns
// -&gt; Hello John
// -&gt; Hello Jane
// -&gt; ..
</pre>
<p>Again, you can access variables outside the scope of the Closure by using the <em>use</em> clause:</p>
<pre class="brush: php; title: ; notranslate">
// Set a multiplier
$multiplier = 3;

// Create a list of numbers
$numbers = (1,2,3,4);

// Use array_walk to iterate
// through the list and multiply
array_walk($numbers, function($number) use($multiplier){
	echo $number * $multiplier;
});
</pre>
<p>In the example above, it probably wouldn&#8217;t make sense to create a function to just multiply two numbers together. If you were to create function to do a job like this, then come back to the code a while later you will probably be thinking why did you bother create a globally accessible function only to be used once? By using a Closure as the callback, we can use the function once and then forget about it.</p>
<h2>Real life usage</h2>
<p>So we&#8217;ve established that Lambdas and Closures are anonymous functions that can be used as throw away bits of functionality that don&#8217;t pollute the global namespace and are good to use as part of a callback.</p>
<p>A popular example of the use of these types of functions is in routing requests within modern frameworks. <a href="http://laravel.com/docs/routing">Laravel</a> for example, allows you to do the following:</p>
<pre class="brush: php; title: ; notranslate">
Route::get('user/(:any)', function($name){
  return &quot;Hello &quot; . $name;
});
</pre>
<p>The code above simply matches a URL like <em>/user/philip</em> and returns a greeting.</p>
<p>This is a very basic example, but it highlights how a Closure can be utilised in a very useful situation.</p>
<h2>Conclusion</h2>
<p>So hopefully that was a good explanation of Lambdas and Closures.</p>
<p>Lambdas and Closures seem like two very deep Computer Science terms if you are a newbie programmer. However, it&#8217;s actually not that complicated at all. Both Lambdas and Closures are simply anonymous functions that are useful for one offs or where it doesn&#8217;t make sense to define a function.</p>
<p>Lambdas and Closures are fairly new to PHP and they don&#8217;t follow exactly the same usage as in other languages. If you are at all familiar with Javascript, you will see anonymous functions used a lot. In particular, you will see a lot of good examples in jQuery. Once you can recognise the pattern, it makes reading code a lot easier because you not only understand what is going on, but also understand why it was written like that in the first place and what the developer was trying to achieve through her decisions.</p>
<p><a href="http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/">What are PHP Lambdas and Closures?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with PHPUnit</title>
		<link>http://culttt.com/2013/03/13/getting-started-with-phpunit/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-phpunit</link>
		<comments>http://culttt.com/2013/03/13/getting-started-with-phpunit/#comments</comments>
		<pubDate>Wed, 13 Mar 2013 08:27:47 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2871</guid>
		<description><![CDATA[<p>On Monday I introduced the concept of Test Driven Development. Test Driven Development is a programming methodology that promotes writing unit tests before you write your actual code. This means that every aspect of your code will have a explicit test to ensure that it is functioning correctly. By writing your tests from the outset, [...]</p><p><a href="http://culttt.com/2013/03/13/getting-started-with-phpunit/">Getting started with PHPUnit</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://culttt.com/wp-content/uploads/2013/03/Getting-started-with-PHPUnit.jpg" alt="Getting started with PHPUnit" /><br />
On Monday I introduced the concept of <a href="http://culttt.com/2013/03/11/what-is-test-driven-development">Test Driven Development</a>. Test Driven Development is a programming methodology that promotes writing unit tests before you write your actual code. This means that every aspect of your code will have a explicit test to ensure that it is functioning correctly. By writing your tests from the outset, you are left with an automated testing process that can be run during <a href="http://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration</a>.</p>
<p><a href="https://github.com/sebastianbergmann/phpunit/">PHPUnit</a> is the de-factor standard for Unit testing PHP. PHPUnit is essentially a framework for writing tests and the necessary tools that you will need to run tests and analyse the results.</p>
<p>In this post I will show you how to get up and running with PHPUnit and how it should fit into your workflow.</p>
<h2>Install PHPUnit via Composer</h2>
<p>The first thing we need to do is to install PHPUnit through Composer. By doing this, we can set PHPUnit as a dependancy on our project which can managed easily going forward.</p>
<p>If you are unfamiliar with Composer, take a look at <a href="http://culttt.com/2013/01/07/what-is-php-composer/">What is PHP Composer?</a></p>
<p>So firstly, create a new folder and a new composer.json file. In your Composer file, write the following:</p>
<pre class="brush: jscript; title: ; notranslate">
{
  &quot;require&quot;: {
    &quot;phpunit/phpunit&quot;: &quot;3.7.*&quot;
  }
}
</pre>
<p>Next, open Terminal and run:</p>
<pre class="brush: bash; title: ; notranslate">
$ composer install
</pre>
<p>Composer should now automatically download PHPUnit into your project and set up all the required files. If everything has worked correctly you should now have a <em>vendor</em> folder that contains PHPUnit amongst other things.</p>
<h2>Setting up a test</h2>
<p>Now that you have PHPUnit set up, we can start writing some tests.</p>
<p>When writing tests, you should keep them all together in the same directory. So first, move back to the root of your project and create a new directory called <em>tests</em>.</p>
<p>For this tutorial, I&#8217;m going to be creating a Car class. So within your tests directory, create a file called CarTest.php. It&#8217;s common practice to name your test classes after the real class but with &#8220;Test&#8221; appended. You don&#8217;t have to do this, but it will make things a lot easier when you come back to it or another developer has to continue your work.</p>
<p>In the CarTest.php file, create a new Class that extends PHPUnit.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class CarTest extends PHPUnit_Framework_TestCase{

}
</pre>
<h2>Writing the first test</h2>
<p>Next we will write our first test. The first test I want to write is to test that the name of the car is getting set correctly when the Class is instantiated. To do that, we can write a test like this.</p>
<pre class="brush: php; title: ; notranslate">
public function testName(){

}
</pre>
<p>First we create a new test method. You should always start your test method names with &#8220;test&#8221; and then describe your test using <a href="http://en.wikipedia.org/wiki/CamelCase">camel case</a>.</p>
<p>Next we can create a new instance of the Car class</p>
<pre class="brush: php; title: ; notranslate">
public function testName(){
  // Create new Car and pass in a name
  $car = new Car(&quot;Murcielago&quot;);
}
</pre>
<h2>Watching a test fail</h2>
<p>Hopefully you will have noticed that we haven&#8217;t actually created the Car class so it would be impossible to create a new instance of it. So now that we have written our test, we can run PHPUnit and watch it fail.</p>
<p>Open up Terminal again and run the following command:</p>
<pre class="brush: bash; title: ; notranslate">
vendor/bin/phpunit tests/CarTest.php 
</pre>
<p>This simply runs PHPUnit on our CarTest.php file. You can alias the PHPUnit command so you don&#8217;t have to type out the full path name.</p>
<p>Once you have run that test, you should have got the following error:</p>
<pre class="brush: bash; title: ; notranslate">
PHP Fatal error:  Class 'Car' not found
</pre>
<p>As you probably guessed, the test failed because there is no such thing as the Car class.</p>
<h2>Writing just enough code</h2>
<p>To make the test pass, we need to actually create a Car class. So back in the root of your project, create a new file called Car.php and write the following:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class Car {

}
</pre>
<p>Next, in your CarTest.php file, add the following line to include the Car class.</p>
<pre class="brush: php; title: ; notranslate">
include 'Car.php';
</pre>
<p>Next run the same test again. You can just hit the up arrow key in Terminal to run recently run commands again.</p>
<p>If you have done everything right, the test should pass. Congratulations, you&#8217;ve just taken your first big step in Test Driven Development!</p>
<p>Let&#8217;s quickly review what we have done so far.<br />
<em>First</em>, we wrote the test for our required functionality.<br />
<em>Second</em>, we watched the test fail.<br />
<em>Third</em>, we wrote just enough code to make the test pass.</p>
<p>Hopefully if Test Driven Development seemed a bit foreign to you at the start of the this tutorial than the process that we&#8217;ve just stepped through should clear it up. Essentially, Test Driven Development is just breaking down the problem, creating a test to ensure what we are hoping to achieve will work, watching it fail and then writing the code to make it pass. In this way we can be sure that what we are writing is going to be working exactly as we expected it to do. In the future, if we ever write code that breaks this test, we will be alerted to it by running PHPUnit.</p>
<h2>Assertions</h2>
<p>If you flick back to your Terminal and read the output, you should notice following line:</p>
<pre class="brush: bash; title: ; notranslate">
OK (1 test, 0 assertions)
</pre>
<p>Our test passed, but we didn&#8217;t actually test to see if the name was getting set correctly.</p>
<p>We can now write the test to <em>assert</em> if the name is getting set correctly or not.</p>
<p>Go back to your CarTest.php file and add the following to the testName() method:</p>
<pre class="brush: php; title: ; notranslate">
public function testName(){
  // Create new Car and pass in a name
  $car = new Car(&quot;Murcielago&quot;);
  // Get the car name
  $result = $car-&gt;name();
  // Assert that the name has been set correctly
  $this-&gt;assertEquals(&quot;Murcielago&quot;, $result);
}
</pre>
<p>Now run the test again in Terminal. You should get the following error.</p>
<pre class="brush: bash; title: ; notranslate">
PHP Fatal error:  Call to undefined method Car::name()
</pre>
<p>Looks like we haven&#8217;t created the name method yet. Open up Car.php and create the name method.</p>
<pre class="brush: php; title: ; notranslate">
public function name(){
}
</pre>
<p>Now run the test again. You should get the following error.</p>
<pre class="brush: bash; title: ; notranslate">
Failed asserting that null matches expected 'Murcielago'.
Tests: 1, Assertions: 1, Failures: 1.
</pre>
<p>Perfect! Our test failed for exactly the reason we were looking for. The name of the car is not being set. Next we can write the code to make the pass test.</p>
<p>First declare the name as a property of the class:</p>
<pre class="brush: php; title: ; notranslate">
protected $name;
</pre>
<p>Next add a construct method that set&#8217;s the name when the class is instantiated.</p>
<pre class="brush: php; title: ; notranslate">
public function __construct($name){
  $this-&gt;name = $name;
}
</pre>
<p>Next return the name within the name method.</p>
<pre class="brush: php; title: ; notranslate">
public function name(){
  return $this-&gt;name;    
}
</pre>
<p>Next run your test again. You should get the following result:</p>
<pre class="brush: php; title: ; notranslate">
OK (1 test, 1 assertion)
</pre>
<p>Woohoo, our test passed! So as you can see, first we wrote our test and let it fail, then we wrote just enough code to make it pass.</p>
<h2>Conclusion</h2>
<p>This is really just scratching the surface of Test Driven Development with PHPUnit. In the future I will write more in-depth tutorials on how you should write tests for each aspect of your application.</p>
<p>Hopefully for now, you should have a strong grasp of Test Driven Development, you&#8217;ve seen how it works in real life and I&#8217;ve shown you how to get started.</p>
<p>Now go write some tests.</p>
<p><a href="http://culttt.com/2013/03/13/getting-started-with-phpunit/">Getting started with PHPUnit</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/03/13/getting-started-with-phpunit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is Test Driven Development?</title>
		<link>http://culttt.com/2013/03/11/what-is-test-driven-development/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-is-test-driven-development</link>
		<comments>http://culttt.com/2013/03/11/what-is-test-driven-development/#comments</comments>
		<pubDate>Mon, 11 Mar 2013 08:27:20 +0000</pubDate>
		<dc:creator>Philip Brown</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://culttt.com/?p=2868</guid>
		<description><![CDATA[<p>Over the past couple of years, there has been a strong shift in the development community to move towards Continuous Integration. Continuous Integration (CI) is where a team of developers will push changes or new features multiple times per day. The benefits of rapid deployment is that new features and fixes can be applied to [...]</p><p><a href="http://culttt.com/2013/03/11/what-is-test-driven-development/">What is Test Driven Development?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></description>
				<content:encoded><![CDATA[<p><img alt="What is Test Driven Development?" src="http://culttt.com/wp-content/uploads/2013/03/What-is-Test-Driven-Development-.jpg" /><br />
Over the past couple of years, there has been a strong shift in the development community to move towards Continuous Integration. <a href="http://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration</a> (CI) is where a team of developers will push changes or new features multiple times per day. The benefits of rapid deployment is that new features and fixes can be applied to the production server much quicker.</p>
<p>In the fast paced world of software development, there will always be bugs in code. When you are deploying to the live server multiple times per day, you increase the likelihood that you have introduced a bug in new code, or you have broken something in the existing architecture.</p>
<p>One of the key components of Continuous Integration is having automated tests run through your code to check that everything is working as it should.</p>
<p>Setting up tests for code that you have already written can seem laborious and time consuming. Test Driven Development (TDD) is a software development process that promotes writing tests from the outset.</p>
<p>In this post I will introduce the concept of Test Driven Development, how it works and why you should consider changing your workflow.</p>
<p>Whilst there is far more to Continuous Integration than a testing framework, it is an important first step if you want to move your software into a more stable and fast moving architecture.</p>
<h2>What is Test Driven Development?</h2>
<p>Test Driven Development (TDD) is the process of writing tests during the development of software. Typically, TDD will break each task of the development into individual <em>units</em>. A test is then written which will ensure that the unit behaves as expected.</p>
<p>Over the course of developing the software, the developer will build up a framework of tests for each individual component of the architecture. These automated tests can be run periodically to ensure that each individual component is still behaving as expected.</p>
<h2>Why should I use Test Driven Development?</h2>
<p>Whilst Test Driven Development makes the actual writing of code slower, there are a number of advantages to taking this approach.</p>
<p>Firstly, you ensure that your code is working exactly how you mean it to. Often code will seem to work correctly, when in fact there is some underlying reason why it will fail under a certain condition. Test Driven Development looks to remove this problem by ensuring that each individual component is working correctly.</p>
<p>Secondly, testing an application through a browser can be extremely time consuming and it&#8217;s pretty easy to overlook or miss a serious bug. Test Driven Development enables you to set up test cases to test each element of validation, database requesting and all of your business logic so that each individual component gets tested.</p>
<p>And thirdly, when you come to make changes to your code in the future you could unwittingly make a change that breaks another mission critical part of your application. When making changes, you are only going to be manually testing the areas of the software that you think you will have effected. It&#8217;s really easy to forget about some underlying structure once an application becomes complicated. Test Driven Development will highlight exactly where something has broken, and allows you ship your latest release without worrying that you have left something broken.</p>
<p>An excellent analogy for Test Driven Development is, TDD is like brakes on your car. Without breaks on a car, you would be forced to drive really slowly. However, because breaks allow you to control when you stop, it allows you to drive much more freely. Test Driven Development removes all of the stress of shipping broken code, and allows you to get on with the job of improving your application.</p>
<h2>What is the Test Driven Development cycle?</h2>
<p>The Test Driven Development cycle is a bit of a departure from the normal way of writing code so it can take some getting used to.</p>
<h3>Write a test</h3>
<p>Before you write any actual code, you need to write your test so you can watch it fail. Writing the test first ensures that you can confidently say that you made the test pass for the right reasons.</p>
<h3>Watch it fail</h3>
<p>At this point it&#8217;s pretty obvious it&#8217;s going to fail because there is nothing to test! This incremental approach keeps you on the right track of breaking each component down in to it&#8217;s smallest unit.</p>
<h3>Write the bare minimum code to make it pass</h3>
<p>Now you need to write the bare minimum amount of code to make the test pass. It&#8217;s important that you only write enough to make the test pass because you will need to write additional tests for any additional code you write.</p>
<h3>Refactor</h3>
<p>During the process of writing code in Test Driven Development, you will probably need to refactor your code every so often. Writing code that makes tests pass isn&#8217;t always as optimum as it could be.</p>
<p>Every so often, loop back and evaluate how you can rewrite something to improve it and keep it <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>. Fortunately you don&#8217;t have to worry about breaking any of your code during refactoring because you can just run your tests again.</p>
<h2>Terminology</h2>
<p>As with just about everything, Test Driven Development introduces terminology that you may be unfamiliar with. It&#8217;s difficult to understand something if you don&#8217;t understand the terminology and so here is an explanation of some of the common terms that you will come across.</p>
<h3>Unit Testing</h3>
<p>As covered above, Unit Testing is where you break down you code into small individual components that can be tested independently. By testing each individual component, you ensure that your tests are passing because the unit is behaving correctly and not because it is tied to another unit of code.</p>
<h3>Integration Testing</h3>
<p>Once you have a number of Units that have all been individual tested, you can put them all together and test them as a group. This is known as Integration Testing. This ensures that all of the individual components are working together correctly.</p>
<h3>Validation Testing</h3>
<p>Finally Validation Testing is usually the process where your code is given to software testers to ensure that the feature is working as intended. This can often be achieved by doing sanity checks within the browser.</p>
<h3>Test Stubs</h3>
<p>In complex applications, it&#8217;s rare to find components that aren&#8217;t tied or coupled to other components in some way. Often the part of the code that you want to test is dependant on some other part of the code.</p>
<p>For example, when you are testing returning results from a database, you will need to test the Model independently from the Database.</p>
<p>A Test Stub acts as a replacement to the dependancy. This allows you to test your code without having to actually make real calls to a database.</p>
<h3>Mock Objects</h3>
<p>Similar to Test Stubs, Mock Objects act as a replacement for dependant objects when running Unit Tests. Mock Objects are useful when you want to simulate a state of your application that can only be achieved with the presence of certain Objects.</p>
<p>For example, say you had integrated Twitter into your application and you need to simulate interaction with Twitter without having to actually make a connection for each test. Instead, you could create a Mock Object that would simulate the interaction with Twitter and allow you to Unit Test your code without depending on the external service.</p>
<h3>Build Server</h3>
<p>Deploying from a Build Server is a common approach taken by larger application projects. Essentially a Build Server is just a dedicated server the manages deploying changes to production.</p>
<p>When you have many developers working on a project together, each developer&#8217;s environment can slightly differ. Having a Build Server ensures is a last level of defences for catching bugs.</p>
<p>For a more in depth explanation of why Build Servers are important, take a look <a href="http://www.joelonsoftware.com/articles/fog0000000023.html">Daily Builds Are Your Friend</a> by <a href="https://twitter.com/spolsky">Joel Spolsky</a>.</p>
<h2>Conclusion</h2>
<p>Test Driven Development can seem like a big departure from your current workflow as you need to introduce a significant amount of extra work just to write code. However, when you come to work on big projects and collaborate with other developers, writing tests starts to become a necessity.</p>
<p>Test Driven Development shouldn&#8217;t completely slow down your productivity. Finding the right balance of writing tests and writing code is important to ensuring that you can actually get work done and ship your product.</p>
<p>But it&#8217;s hard to argue against being able to quickly test your entire codebase to ensure that everything is working correctly.</p>
<p><a href="http://culttt.com/2013/03/11/what-is-test-driven-development/">What is Test Driven Development?</a> was written by <a rel="author" href="http://culttt.com/author/philipbrown/">Philip Brown</a> on <a href="http://culttt.com">Culttt - Articles on business, technology and the Internet</a></p>]]></content:encoded>
			<wfw:commentRss>http://culttt.com/2013/03/11/what-is-test-driven-development/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced

 Served from: culttt.com @ 2013-05-25 00:35:42 by W3 Total Cache -->