<?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>Dave Gardner - PHP Developer &#187; PHP</title>
	<atom:link href="http://www.davegardner.me.uk/blog/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.davegardner.me.uk/blog</link>
	<description>Just behind the bleeding edge of PHP.</description>
	<lastBuildDate>Fri, 02 Jul 2010 08:25:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP and Cassandra</title>
		<link>http://www.davegardner.me.uk/blog/2010/07/02/php-and-cassandra/</link>
		<comments>http://www.davegardner.me.uk/blog/2010/07/02/php-and-cassandra/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 08:25:35 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[cassandra]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[phplondon]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=105</guid>
		<description><![CDATA[Yesterday (1st July) I presented for the first time at the PHP London user group. It was a gentle introduction; a five minute &#8220;lightening&#8221; talk slot. I spoke about Cassandra, giving a short introduction to using it with PHP.

To summarise my main points from the talk (perhaps something I should have done in the talk!)

Cassandra [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday (1st July) I presented for the first time at the <a href="http://www.phplondon.org/" target="_blank">PHP London user group</a>. It was a gentle introduction; a five minute &#8220;lightening&#8221; talk slot. I spoke about <a href="http://cassandra.apache.org/" target="_blank">Cassandra</a>, giving a short introduction to using it with PHP.</p>
<div id="__ss_4664596" style="margin: 20px 0pt; width: 425px;"><object id="__sse4664596" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cassandphp-phplondon-100702015458-phpapp02&amp;stripped_title=php-and-cassandra" /><param name="name" value="__sse4664596" /><param name="allowfullscreen" value="true" /><embed id="__sse4664596" type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=cassandphp-phplondon-100702015458-phpapp02&amp;stripped_title=php-and-cassandra" name="__sse4664596" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<p>To summarise my main points from the talk (perhaps something I should have done <em>in</em> the talk!)</p>
<ul>
<li>Cassandra is a &#8220;highly scalable second-generation distributed database&#8221;</li>
<li>It can be considered a schema-less database insofar that each row can have different columns</li>
<li>Cassandra is designed to be both fault tolerant and horizontally scalable &#8211; both read and write throughput go up linearly as more boxes are added to the cluster</li>
<li>I think the best way of accessing Cassandra from PHP is directly via the <a href="http://wiki.apache.org/cassandra/API" target="_blank">Thrift API</a>. This allows a beginner to learn about the core functionality of Cassandra including its limitations</li>
<li>Cassandra has Hadoop support which means that Hadoop Map Reduce jobs (a scalable, distributed mechanism for processing data) can read and write to Cassandra*</li>
<li>Cassandra does not have any query language (as opposed to MySQL or <a href="http://www.mongodb.org/" target="_blank">MongoDB</a> which both allow you to query data in different ways)</li>
<li>When designing your data model, I think its easiest to try to forget about SQL and concentrate on how Cassandra works (don&#8217;t design a relational schema and then &#8220;port&#8221; it over)</li>
</ul>
<p>* As of version 0.7!</p>
<p>Overall, I think Cassandra is a very useful tool. Whether it fits your use case or not is another matter!</p>
<p>If you&#8217;re interested in learning more about using Cassandra in a PHP project, I recommend the following starting points:</p>
<ol>
<li>Using Cassandra with PHP<br />
<a href="https://wiki.fourkitchens.com/display/PF/Using+Cassandra+with+PHP" target="_blank">https://wiki.fourkitchens.com/display/PF/Using+Cassandra+with+PHP</a></li>
<li>WTF is a SuperColumn? An Intro to the Cassandra Data Model<br />
<a href="http://arin.me/blog/wtf-is-a-supercolumn-cassandra-data-model" target="_blank">http://arin.me/blog/wtf-is-a-supercolumn-cassandra-data-model</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2010/07/02/php-and-cassandra/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Caching dependency-injected objects</title>
		<link>http://www.davegardner.me.uk/blog/2010/03/22/caching-dependency-injected-objects-with-php/</link>
		<comments>http://www.davegardner.me.uk/blog/2010/03/22/caching-dependency-injected-objects-with-php/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 09:38:49 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[dependencyinjection]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[memcache]]></category>
		<category><![CDATA[sleep]]></category>
		<category><![CDATA[wakeup]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=89</guid>
		<description><![CDATA[This blog posts talks about cacheing and retrieving objects in PHP, for example by using Memcache, where the objects themselves have a number of dependencies. It includes using the PHP magic methods __sleep and __wakeup to manage serialisation. It also discusses mechanisms for reinjecting dependencies on wakeup, including a mechanism that keeps the Inversion of Control (IoC) principle central to most DI "containers".]]></description>
			<content:encoded><![CDATA[<p>This blog posts talks about caching and retrieving objects in PHP (eg: via <a href="http://php.net/manual/en/book.memcache.php" target="_blank">Memcache</a>) where the objects themselves have a number of <strong>injected dependencies</strong>. It includes using the PHP magic methods __sleep and __wakeup to manage <a href="http://uk.php.net/manual/en/function.serialize.php" target="_blank">serialisation</a>. It also discusses mechanisms for re-injecting dependencies on wakeup via a method that maintains <a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">Inversion of Control</a> (IoC).</p>
<p>This post covers:</p>
<ul>
<li><a href="#sample-system">A sample OOP system that we will discuss</a></li>
<li><a href="#di">The basics of Dependency Injection</a></li>
<li><a href="#putting-objects-to-sleep">Putting objects to sleep</a></li>
<li><a href="#waking-objects-up">Waking objects up</a></li>
</ul>
<h3><a name="sample-system">Sample system</a></h3>
<p>To illustrate the idea, I&#8217;ll use a simple domain model where we have a <strong>userList</strong> object (iterator) containing a number of <strong>user</strong> objects. Each user has an injected <strong>userDao</strong> dependency which is used for lazy-loading <strong>usageHistory</strong>, on request.</p>
<pre class="code">class userList
{
    public function current() { }

    public function key() { }

    public function next() { }

    public function rewind() { }

    public function valid() { }

    public function count() { }
}

class user
{
    private $usageHistory;

    public function __construct($dao, $userDataRow)
    {
        $this-&gt;dao = $dao;
        $this-&gt;usageHistory = NULL;
    }

    public function getUsageHistory()
    {
        if ($this-&gt;usageHistory === NULL)
        {
            $this-&gt;usageHistory = $this-&gt;dao-&gt;lazyLoadHistory($this);
        }
        return $this-&gt;usageHistory;
    }
}

class userDao
{
    public function __construct($database, $cache, $logger)

    public function getList() { }

    public function lazyLoadHistory() { }
}

class usageHistory
{
}</pre>
<h3><a name="di">Dependency Injection</a></h3>
<p>A sample invocation of this simple system might be to ask the DAO for a user list object. To create a DAO object we will almost certainly need to pass in a bunch of dependencies such as database services, caching services and logging services.</p>
<p>I&#8217;m using a DI container to create objects. To get a really quick idea of what these are about you can imagine doing this:</p>
<pre class="code">$diContainer = new diContainer();
$userDao = $diContainer-&gt;getInstance('userDao');</pre>
<p>Instead of this:</p>
<pre class="code">$configuration = new systemConfig();

$database = new mysqlDatabaseConnection($configuration);
$cache = new memcacheConnection($configuration);
$logger = new firebugLogger();

$userDao = new userDao($database, $cache, $logger);
$userList = $userDao-&gt;getList();</pre>
<p>The key idea is that the DI container will build the object graph for you. For each dependency needed it will go away and fetch that, building any other dependencies of those objects and so on recursively up the tree.</p>
<p>I&#8217;m using an annotation system to power <a href="http://www.davegardner.me.uk/blog/2009/11/23/php-dependency-strategies-dependency-injection-and-service-locator/" target="_blank">my own DI container</a>; making the whole process simple and configuration-light.</p>
<h3><a name="putting-objects-to-sleep">Putting objects to sleep</a></h3>
<p>Caching is a very handy tool to improve the performance of applications. Storing objects in a cache (for example Memcache) prevents us having to go to database each time. Memcache is a very simple system; a key-value store. You give it some data (less than 1MB) and it stores it for you until you ask for it again. Storing objects is slightly more complex than simple strings; with objects you need to <strong>serialise</strong> them. Memcache actually does this for you (you don&#8217;t need to call serialize() first).</p>
<p>However caching objects can be problematic. Whenever you start to really use the power of OOP you inevitably end up with complex object graphs. Our <strong>user</strong> object, for example, <em>contains</em> a <strong>userDao</strong> object. This in turn contains a <strong>database</strong> service object, a<strong> cache </strong>service object and a <strong>logging </strong>service object. Some of <em>these</em> objects have their own dependencies! For example the database service object contains a <strong>configuration</strong> object.</p>
<p>The key point here is that by default, when we serialise a user object we will be serialising all the internal properties, including all the dependencies. This is undesirable.</p>
<p>This is where PHP&#8217;s built-in magic <strong>__sleep</strong> method comes to the rescue. Using __sleep we can <em>tell</em> PHP what we<em> do</em> want to store. Let&#8217;s assume our user object has the following properties:</p>
<pre class="code">class user
{
    private $dao;
    private $name;
    private $age;
    private $email;
    private $phoneNumber;
    private $usageHistory;
}</pre>
<p>What we&#8217;ll do is tell PHP what we want to save.</p>
<pre class="code">class user
{
    public function __sleep()
    {
        return array('name', 'age', 'email', 'phoneNumber');
    }
}</pre>
<p>Now we can serialise and/or cache objects without the overhead of complex dependency graphs.</p>
<h3><a name="waking-objects-up">Waking objects up</a></h3>
<p>When it comes to restoring objects, for example via Memcache::get or via unserialize(), we will end up with a user object that has a valid name, age, email and phoneNumber property.  What we won&#8217;t have is the <strong>DAO</strong> dependency or the <strong>usageHistory</strong> property.  It is important to realise that the class constructor will <em>not</em> be called when the object is unserialised.</p>
<p>For pure simplicity we can use PHP&#8217;s built-in magic <strong>__wakeup</strong> method to execute code on unserialisation.</p>
<pre class="code">class user
{
    public function __wakeup()
    {
        $this-&gt;usageHistory = NULL;
        $diContainer = new diContainer();
        $userDao = $diContainer-&gt;getInstance('userDao');
    }
}</pre>
<p>This is handy for ensuring that the usageHistory property is properly set to NULL (so it will lazy-load). The problem with this approach is that we lose the Inversion of Control. Instead of <em>injecting</em> the dependencies, we are instead looking them up; we have a tightly coupled dependency to the DI container. One of the key points of DI is that the objects themselves shouldn&#8217;t really know or care about the DI container.</p>
<p>When constructing objects using the DI container we never directly use the &#8220;new&#8221; keyword to create objects &#8211; instead we rely on the DI container to do this for us. This supplies all dependencies as <strong>parameters</strong>. However we can&#8217;t replace the call to __wakeup; and therefore we can&#8217;t inject dependencies here.</p>
<h3>Restoring dependencies</h3>
<p>To ensure that dependencies are restored correctly I use a &#8220;magic&#8221; method <strong>__restoreDependencies</strong>. Ok so it&#8217;s not actually that magic; PHP doesn&#8217;t call it automatically! However the serialisation/unserialisation in my application is localised within my <strong>cache</strong> object. Therefore what I can do is adjust my cache::get method:</p>
<pre class="code">class cache
{
    public function get($key)
    {
        $value = $this-&gt;memcache-&gt;get($key);
        if (is_object($value) &amp;&amp; $value instanceof cacheable)
        {
            $this-&gt;diContainer-&gt;wakeup($value);
        }
    }
}</pre>
<p>To make life easy I actually use a &#8220;cacheable&#8221; interface that objects must implement in order to be stored in cache. This formality really just ensures that no one tries to cache objects without making sure they think of the implications on dependencies. The cacheable interface simply ensures that an object has a __restoreDependencies() method.</p>
<p>The (bespoke) DI container has a &#8220;wakeup&#8221; method that will:</p>
<p>1. Call the __restoreDependencies() method injecting any required services (dependency objects)</p>
<p>2. If the __restoreDependencies() method returns an array of other objects, call the wakeup() method on those objects as well. This can repeat recursively if required.</p>
<p>The second point here ensures that we can cache an entire <strong>userList </strong>object and wake it up effectively.  The <strong>userList </strong>object&#8217;s __restoreDependencies() method would return an array of all <strong>user </strong>objects that need waking up.</p>
<p>The result is that I can cache complex object graphs <em>without</em> dependencies, but have these dependencies automatically &#8220;fixed&#8221; when objects are retrieved from cache. The objects themselves don&#8217;t really know anything about the process. Instead all they need to do is define a simple interface which defines the required dependencies.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2010/03/22/caching-dependency-injected-objects-with-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Christmas reading list</title>
		<link>http://www.davegardner.me.uk/blog/2009/12/18/christmas-reading-list/</link>
		<comments>http://www.davegardner.me.uk/blog/2009/12/18/christmas-reading-list/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 10:13:35 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[christmas]]></category>
		<category><![CDATA[reading]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=42</guid>
		<description><![CDATA[It's that time of year when you're wondering what Santa will bring you on Christmas day! I've compiled a list of programming books you definitely want Santa to bring.]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s that time of year when you&#8217;re wondering what Santa will bring you on Christmas day! Taking the <a href="http://repeatgeek.com/tools/6-books-every-programmer-should-own/">ever-popular </a>idea of &#8220;n books every programmer should read&#8221;, I decided to compile my own list.  If you&#8217;re lucky, Santa might bring you one of these.</p>
<h3>Coders at Work</h3>
<p><img class="size-medium wp-image-43" style="float:left;margin-right: 60px;" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2009/12/coders-at-work-206x300.jpg" alt="Coders at Work" width="206" height="300" /> An absolute barnstorming programming book and exactly the sort of book you could actually read on Christmas day; honest. A series of insightful interviews with top programming minds.<br />
<a href="http://www.davegardner.me.uk/reading/coders-at-work/">Find out more</a></p>
<h3 style="padding-top:20px;">Mythical Man Month</h3>
<p><img class="alignnone size-medium wp-image-45" style="float:left;margin-right: 60px;" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2009/12/mmm-201x300.jpg" alt="Mythical Man Month" width="201" height="300" /> Another book that&#8217;s light on technical details (reams of code) but heavy on insight. Fred Brooks&#8217; classic essays still resonate today, 34 years after the book first appeared.<br />
<a href="http://www.davegardner.me.uk/reading/mythical-man-month/">Find out more</a></p>
<h3 style="padding-top:20px;">Patterns of Enterprise Application Architecture</h3>
<p><img class="alignnone size-medium wp-image-44" style="float:left;margin-right: 60px;" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2009/12/enterprisepatterns-239x300.jpg" alt="Patterns of Enterprise Application Architecture" width="239" height="300" />Arguably a bit heavy going for Christmas day but probably the most useful book I&#8217;ve read in the last six months. I&#8217;m constantly referring back to it for details and have taken to including references to the text within my comments when writing code. Santa wouldn&#8217;t dissapoint if he gave you this.<br />
<a href="http://www.davegardner.me.uk/reading/patterns-of-enterprise-applicati/">Find out more</a></p>
<p><span style="clear:both;display:block;padding:20px 0;font-size:22px;">Have a great Christmas! See you in 2010.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2009/12/18/christmas-reading-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP dependency strategies: dependency injection and service locator</title>
		<link>http://www.davegardner.me.uk/blog/2009/11/23/php-dependency-strategies-dependency-injection-and-service-locator/</link>
		<comments>http://www.davegardner.me.uk/blog/2009/11/23/php-dependency-strategies-dependency-injection-and-service-locator/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 10:49:17 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[dependencyinjection]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[servicelocator]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=17</guid>
		<description><![CDATA[This post explores three possible strategies that should help create good quality, uncoupled code: Simple Dependency Injection (DI), the Service Locator pattern and a DI framework. This includes a bespoke implementation of a DI framework.]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;m hoping to answer my own question: <strong>what strategy shall I use for handling dependencies in my new project?</strong> I&#8217;m going to explore three possible strategies that should help create good quality, uncoupled code:</p>
<ol>
<li><a href="#strategy1">Simple Dependency Injection (DI)</a></li>
<li><a href="#service-locator">The Service Locator pattern</a></li>
<li><a href="#di-framework">A DI framework</a></li>
</ol>
<p>This includes a <a href="#bespoke-service-injector">bespoke implementation of a DI framework for PHP</a> that automatically creates configuration by conducting a simplistic static analysis of code.</p>
<h3>What are dependencies</h3>
<p>Consider the following code. This simple application comprises a simple <strong>event</strong> domain object combined with a <a target="_blank" href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html">Data Access Object</a> (DAO) that deals with persistance.</p>
<h5>event.class.php</h5>
<pre class="code">
class event
{
    private $name;
    private $cost;
    private $eventDate;

    /**
     * @param array $row Information on this event from DAO
     */
    public function __construct($row)
    {
        $this->name = $row['name'];
        $this->cost = new money($row['cost']);
        $this->eventDate = new date($row['date']);
    }

    public function __toString()
    {
        return "EVENT: {$this->name}\nCOST:  {$this->cost}\nDATE:  {$this->eventDate}\n";
    }
}
</pre>
<h5>eventDao.class.php</h5>
<pre class="code">
class eventDao
{
    public function getById($id)
    {
        $db = new database('localhost','mydb','user','password');

        $row = $db->fetchAll(
           "SELECT name, cost, date FROM events WHERE id = ".$db->quote($id);
        );

        return new event($row);
    }
}
</pre>
<p>An <strong>event</strong> object is dependant on a <strong>money</strong> object and a <strong>date</strong> object. It needs to create these to function correctly.</p>
<p>An <strong>eventDao</strong> object is dependant on a <strong>database</strong> object and an <strong>event</strong> object. It needs the database object to get the data and it needs to create and return a new event object.</p>
<h3>Why are depedencies problematic?</h3>
<p>Dependencies are not in themselves problematic. It is going to be impossible to write any useful code that doesn&#8217;t have some dependencies. The problem is how we handle those the dependencies. The code example provided above presents the following problems.</p>
<h5>1. It makes testing impossible</h5>
<p>Writing a <a target="_blank" href="http://en.wikipedia.org/wiki/Unit_testing">unit test</a> for the event object will inevitably end up testing the <strong>money</strong> and <strong>date</strong> objects. When we create a new event object we have no control over the creation of those dependent objects. This means our unit test will cross the class boundary and what we end up with is an <a target="_blank" href="http://en.wikipedia.org/wiki/Integration_testing">integration test</a> rather than a unit test. Instead of testing the logic of the specific, isolated &ldquo;unit&rdquo; (our event object), we are instead testing the event object works in relation to the rest of the program.</p>
<p>While it may not seem immediately obvious why that&#8217;s a problem with fairly trivial dependencies such as a money object, the problem is more obvious when considering the DAO. Here we could not test the <strong>getById</strong> method without inadvertantly testing the <strong>database</strong> object. Without a fully-functioning database, setup with the expected data, our unit test will fail. Again, this isn&#8217;t a unit test, it&#8217;s more likely an intergration test or possibly even a <a target="_blank" href="http://en.wikipedia.org/wiki/System_testing">system test</a>.</p>
<h5>2. The objects are tightly coupled</h5>
<p>The <strong>eventDao</strong> class is tightly coupled to the specific concrete classes <strong>event</strong> and <strong>database</strong>. What if we want to use a different database object on our test environment? We can&#8217;t. Of course there&#8217;s ways round this immediate problem without changing too much at all. We could use global constants DATABASE_NAME, DATABASE_USER etc.. Don&#8217;t even go there! Tight coupling makes for <strong>brittle code</strong>. If you&#8217;re not convinced you can <a target="_blank" href="http://www.ibm.com/developerworks/java/library/j-cq05227/index.html">read this article</a> or spend 10 minutes with Google.</p>
<h5>3. It goes against the <a target="_blank" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don&#8217;t Repeat Yourself</a> (DRY) principle</h5>
<p>If we imagine adding some other domain objects and DAOs to our system we will end up repeating the <strong>new database()</strong> line again and again. The same goes for other domain objects that want to represent information internally as a date object.</p>
<h4>An alternative coupling</h4>
<p>Let&#8217;s say you&#8217;ve got this in your DAO instead:</p>
<pre class="code">
        $db = database::getInstance();
</pre>
<p>Same problems! We probably still can&#8217;t test it (unless we have some kind of <em>database::setInstance()</em> method) and it&#8217;s certainly still tightly coupled regardless.</p>
<h3><a name="strategy1">Strategy 1: Dependency Injection</a></h3>
<p>Dependency Injection is very straightforward. In fact it&#8217;s so straightforward you&#8217;ve almost certainly already done it, even if you didn&#8217;t refer to it as DI. Fabien Potencier of Symfony fame <a target="_blank" href="http://fabien.potencier.org/talk/19/decouple-your-code-for-reusability-ipc-2008">explains it expertly in these slides</a>.</p>
<p>To make use of dependency injection, our <strong>eventDao</strong> can be updated to:</p>
<h5>eventDao.class.php</h5>
<pre class="code">
class eventDao
{
    private $db;

    public function __construct($db)
    {
       $this->db = $db;
    }

    public function getById($id)
    {

        $row = $this->db->fetchAll(
           "SELECT name, cost, date FROM events WHERE id = ".$this->db->quote($id);
        );

        return new event($row);
    }
}
</pre>
<pre class="code">
$db = new database('localhost','mydb','user','password');
$dao = new eventDao($db);
$event = $dao->getById(1);
</pre>
<p>We can now <em>test</em> the <strong>getById</strong> method using a <a target="_blank" href="http://www.phpunit.de/manual/current/en/test-doubles.html">mock database object</a> because we are <em>injecting</em> the dependency into the DAO object.</p>
<p>We can&#8217;t, however, isolate testing of the DAO completely because of the <strong>event</strong> dependency. This can be fixed by delegating responsibility for <strong>event</strong> creation to a <a target="_blank" href="http://www.ibm.com/developerworks/library/os-php-designptrns/">Factory</a>.</p>
<h5>eventFactory.class.php</h5>
<pre class="code">
class eventFactory
{
    public function create($row)
    {
        return new event($row);
    }
}
</pre>
<h5>eventDao.class.php</h5>
<pre class="code">
class eventDao
{
    private $db;
    private $eventFactory;

    public function __construct($db, $eventFactory)
    {
       $this->db = $db;
       $this->eventFactory = $eventFactory;
    }

    public function getById($id)
    {

        $row = $this->db->fetchAll(
           "SELECT name, cost, date FROM events WHERE id = ".$this->db->quote($id);
        );

        return $this->eventFactory->create($row);
    }
}
</pre>
<p>Our code is now loosely coupled and we are <a target="_blank" href="http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface">programming to interface</a> (allbeit that I haven&#8217;t actually put any interfaces into the code at this stage!) To <a target="_blank" href="http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface/383954#383954">quote kdgregory from StackOverflow</a>:</p>
<blockquote><p>Programming to an interface is saying &ldquo;I need this functionality and I don&#8217;t care where it comes from.&rdquo;</p></blockquote>
<p>By putting in place a factory for creating objects we can program only to the <em>interface</em> we require. In our <strong>event</strong> class, this means we don&#8217;t have to rely on specific concrete implementations for <strong>date</strong> and <strong>money</strong>, instead we merely require some object that implements <strong>iDate</strong> and <strong>iMoney</strong>, and we can use a factory to <em>make</em> us one of those objects.</p>
<h4>Inversion of Control (IoC)</h4>
<p>It&#8217;s worth noting that by <em>injecting</em> dependencies into the objects we have <em>inverted</em> control, effectively because rather than the procedural/linear style of setting up object and then doing something, we have passed in an object and are executing what almost amounts to a &lsquo;call back&rsquo; on it. The term &ldquo;Inversion of Control&rdquo; seems to come up frequently when reading about DI, although I&#8217;m not sure that it&#8217;s always that clearly explained. Fowler <a target="_blank" href="http://martinfowler.com/bliki/InversionOfControl.html">explains it in this article</a>. There are also some other <a target="_blank" href="http://mikehadlow.blogspot.com/2007/10/what-is-inversion-of-control.html">interesting blog posts on the subject</a>. If you want the short answer on what IoC is, <a target="_blank" href="http://stackoverflow.com/questions/3058/what-is-inversion-of-control/386475#386475">check out this definition.</a></p>
<h4>Object graphs</h4>
<p>Using DI, what we inevitably end up with is a complex <strong>object graph</strong>. An object graph is <a target="_blank" href="http://stackoverflow.com/questions/877157/what-is-an-object-graph-and-how-do-i-serialize-one">simply a set of interconnected objects</a>. In the case of DI, we have lots of interconnected objects since we are passing all our dependencies around as objects &#8211; so we end up with a lot of objects related to a lot of other objects at run time!</p>
<h4>Strengths</h4>
<p>This form of dependency injection is <strong>easy to understand</strong>. We avoid tight coupling, we can test our code and we are programming to interface. All is good!</p>
<h4>Weaknesses</h4>
<p>One of the web apps I work on uses a <a target="_blank" href="http://martinfowler.com/eaaCatalog/frontController.html">Front Controller pattern</a> to handle incoming requests. The bootstrap code looks a bit like this:</p>
<pre class="code">
$fc = new frontController();
$fc->dispatch();
</pre>
<p>If I take the issue of dependency injection to the extreme, slightly insane, but on some level undeniably logical, conclusion, I would have to inject <strong>all</strong> dependencies needed by the <em>entire application</em> into the constructor of the front controller! <a target="_blank" href="http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code/1532254#1532254">This post by Ben Scheirman</a> on StackOverflow gives another example:</p>
<pre class="code">
var svc = new ShippingService(new ProductLocator(),
   new PricingService(), new InventoryService(),
   new TrackingRepository(new ConfigProvider()),
   new Logger(new EmailLogger(new ConfigProvider())));
</pre>
<p>You get the idea.</p>
<p>We could be pragmatic about this and suggest that individual <a target="_blank" href="http://martinfowler.com/eaaCatalog/pageController.html">page controllers</a> are allowed to be tightly coupled to domain objects. However it merely defers the inevitable. </p>
<p>The problem with this strategy is that if you add a dependency to an object, you then have to add it to all parent objects that <em>use</em> that object. This becomes a recursive task so the change causes a ripple effect to other code. The <a target="_blank" href="http://code.google.com/docreader/#p=google-guice&#038;s=google-guice&#038;t=Motivation">documentation to Google Guice</a> explains it quite well (scroll down to the &ldquo;Dependency Injection&rdquo; section &#8211; due to their clever reader thing I can&#8217;t get an anchor link straight to it!) This problem relates to the inherent complexity involved in creating a large <em>object graph</em>.</p>
<blockquote><p>Unfortunately, now the clients of BillingService need to lookup its dependencies. We can fix some of these by applying the pattern again! Classes that depend on it can accept a BillingService in their constructor. For top-level classes, it&#8217;s useful to have a framework. <strong>Otherwise you&#8217;ll need to construct dependencies recursively when you need to use a service</strong></p></blockquote>
<h3><a name="service-locator">Strategy 2: Service Locator</a></h3>
<p>Martin Fowler explains the idea of a service locator in detail in his <a target="_blank" href="http://martinfowler.com/articles/injection.html#UsingAServiceLocator">article on the subject of DI</a>. I&#8217;m going to explain it in the context of a PHP application.</p>
<p>A service locator is a straight forward system whereby objects can &ldquo;look up&rdquo; any dependencies they need from a central source. This gives the following advantages:</p>
<ul>
<li>It is easy to add a dependency to any object</li>
<li>It is easy to replace which dependency is provided <em>project wide</em>, so we are adhering to the DRY principle</li>
<li>It removes tight coupling between objects</li>
</ul>
<p>The simplest service locator may look like:</p>
<h5>serviceLocator.class.php</h5>
<pre class="code">
class serviceLocator
{
    public static function getDatabase()
    {
        return new database();
    }

    public static function getDateFactory()
    {
        return new dateFactory();
    }

    public static function getMoneyFactory()
    {
        return new moneyFactory();
    }

    public static function getEventFactory()
    {
        return new eventFactory();
    }
}
</pre>
<p>Our DAO now becomes:</p>
<h5>eventDao.class.php</h5>
<pre class="code">
class eventDao
{
    public function getById($id)
    {

        $row = serviceLocator::getDatabase()->fetchAll(
           "SELECT name, cost, date FROM events WHERE id = ".$this->db->quote($id);
        );

        return serviceLocator::getEventFactory()->create($row);
    }
}
</pre>
<p>For testing we&#8217;d need to add in equivalent methods like <strong>serviceLocator::setMoneyFactory</strong> and <strong>serviceLocator::setDatabase</strong>.</p>
<p>We can simplify (or complicate depending on your point of view) our service locator by replacing methods like <strong>serviceLocator::getMoneyFactory()</strong> with a more generic <strong>serviceLocator::getService($serviceName)</strong>. We could then configure the service locator in our bootstrap with calls to <strong>serviceLocator::registerService($serviceName, $object)</strong>. If we really wanted to go to town we could use an XML or YAML file to store the details of the dependencies that the service locator provided. For a working system, we probably would want to go this far.</p>
<p>In terms of coupling, we have replaced the coupling of objects from our very first example (where eventDao was tightly coupled to database and event) with equally tight coupling, albeit this time to a <em>single</em> object &#8211; the service locator object. Whether this is desirable will come down to the details of the application. As Fowler points out in his discussion of locator vs injector:</p>
<blockquote><p>The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator. So the decision between locator and injector depends on whether that dependency is a problem.</p></blockquote>
<p>In terms of practical implementations, Mutant PHP has <a target="_blank" href="http://mutantphp.org/blog/2008/06/19/a-service-locator-for-php5/">published an article on this subject</a> which includes a sample service locator class.</p>
<p>The fairly new <a target="_blank" href="http://components.symfony-project.org/dependency-injection/">Symfony Dependency Injection Container</a> appears to be based around the idea of a service locator. I say this because it doesn&#8217;t implement an <em>inversion of control</em> mechanism &#8211; as covered in <a href="#di-framework">strategy 3</a>.</p>
<h4>Strengths</h4>
<p>The service locator provides a <strong>simple</strong> strategy for managing dependencies that is easily understood. It allows for testing and it avoids tight coupling between classes.</p>
<h4>Weaknesses</h4>
<p>The use of a service locator leads to a tight coupling between classes and the service locator itself.</p>
<h3><a name="di-framework">Strategy 3: DI Framework</a></h3>
<p>A dependency injection &ldquo;framework&rdquo; is an alternative strategy for dealing with dependencies to the arguably simpler <a href="#service-locator">service locator</a>. They key idea is to stick with depedency <em>injection</em> (either into the constructor or via a setter), but have some external object (Fowler calls this an &ldquo;assembler&rdquo; in <a target="_blank" href="http://martinfowler.com/articles/injection.html#FormsOfDependencyInjection">his article on the subject</a>) actually deal with managing the dependencies, injecting them into objects as required, without the user having to worry about it.</p>
<p>Now coming from a PHP background, I&#8217;ve searched about for PHP-specific information on DI frameworks. So far, I haven&#8217;t managed to find anything that I feel explains the concept as well as the <a target="_blank" href="http://code.google.com/docreader/#p=google-guice&#038;s=google-guice&#038;t=Motivation">Guice documention</a> does. In terms of responsiblity-driven design, Guice outlines the role of the &ldquo;injector&ldquo; (Fowler&#8217;s &ldquo;assembler&rdquo;):</p>
<blockquote><p>The injector&#8217;s job is to assemble graphs of objects. You request an instance of a given type, and it figures out what to build, resolves dependencies, and wires everything together.</p></blockquote>
<p>This sounds promising, although I&#8217;m not 100% convinced I <em>need</em> a DI framework, I&#8217;m starting to see some advantages. There is an <a target="_blank" href="http://stackoverflow.com/questions/500637/understanding-the-need-for-a-di-framework">interesting discussion on StackOverflow</a> (again!) about the need for a DI framework.</p>
<h4><a name="bespoke-service-injector">A bespoke DI Framework</a></h4>
<p>To help understand the advantages of a DI framework I built my own, which I&#8217;ve rather confusingly called a &ldquo;Service Injector&rdquo;. As Benjamin Eberlei explains in a <a target="_blank" href="http://www.whitewashing.de/blog/articles/117">blog post on the subject of DI</a>:</p>
<blockquote><p>My subjective feeling tells me there are now more PHP DI containers out there than CMS or ORMs implemented in PHP, including two written by myself (an overengineered and a useful one).</p></blockquote>
<p>Having recently read the excellent <a target="_blank" href="http://www.amazon.co.uk/Coders-Work-Reflections-Craft-Programming/dp/1430219483">Coders at Work</a> (go and buy it now if you haven&#8217;t read it), I took some advice from Donald Knuth who said:</p>
<blockquote><p>
The problem is that coding isn&#8217;t fun if all you can do is call things out of a library, if you can&#8217;t write the library yourself.
</p></blockquote>
<p>So I decided to <a href="#source-code">write my own</a>.</p>
<h4>Design motivations</h4>
<p>In Benjamin&#8217;s post, he goes on to say:</p>
<blockquote><p>Its an awesome pattern if used on a larger scale and can (re-) wire a complex business application according to a clients needs without having to change much of the domain code. </p></blockquote>
<p>I think my motivations for DI framework are somewhat different. I don&#8217;t see myself wanting to &ldquo;re-wire&rdquo; an application at a later date.<br />
Ideally I want my logic and wiring to remain clear at the <em>code</em> level; I personally don&#8217;t want to delegate all the wiring to some configurator &#8211; I can see that making any debugging task harder. What I want from a framework is something that will do the hard work for me; something that will supply actual <em>dependencies</em> automatically.</p>
<p>This led me to make the following decisions:</p>
<ul>
<li>I wanted an automated <strong>builder</strong>; something that would look at the code and get the DI framework setup ready to go &#8211; based on class names and interfaces</li>
<li>I wanted to keep <strong>Factory</strong> classes; I think it makes logical sense to have a class who&#8217;s responsibility is to create new objects of type <em>blah</em></li>
</ul>
<h4>A sample application</h4>
<p>At the top level, I can ask the DI framework to create me an object:</p>
<pre class="code">
// setup the service injector
include APP_PATH.'siConfig.php';
$serviceInjector = new serviceInjector();

// ----

// for our test app we'll just pretend we're looking at the details
// of event #1:

$oDao = $serviceInjector->getInstance('eventDao');
$oEvent = $oDao->getById(1);
</pre>
<p>The DAO object is created, along with its dependencies; this all happens simply by annotating the code within the PHPDocumentor style comment blocks:</p>
<pre class="code">
    /**
     * Constructor
     * @param iDatabase $database A service that will allow us to execute SQL
     * @param iEventFactory $eventFactory A service that will create event objects for us
<strong>     * @inject This informs the DI builder to inject constructor parameters on object creation</strong>
     */
    public function __construct(iDatabase $database, iEventFactory $eventFactory)
</pre>
<p>The service injector will find a class that implements iDatabase and iEventFactory and automatically <em>inject</em> these on object creation. The interesting thing is that either of these two services can have their <em>own</em> dependencies. For example, my eventFactory class declaration looks like this:</p>
<pre class="code">
class eventFactory extends factory implements iEventFactory
</pre>
<p>It extends the <a target="_blank" href="http://martinfowler.com/eaaCatalog/layerSupertype.html">Layer Supertype</a> <strong>factory</strong>. The factory base class has a <strong>method</strong> to set its own dependency, again specified via annotation:</p>
<pre class="code">
    /**
     * Set service injector
     * @inject This informs the DI builder to inject method parameters immediately after object creation
     */
    public function setServiceInjector(iServiceInjector $serviceInjector)
    {
        $this->serviceInjector = $serviceInjector;
    }
</pre>
<p>The <em>service injector</em> will happily go away and recursively assemble the required objects and their dependencies.</p>
<h4>The builder</h4>
<p>I have a script that can be executed as part of an automated build process (see my other post) that will create a pure-PHP configuration file for my service injector. It works by conducting a somewhat crude static analysis of the code you tell it to examine. It then works out which classes wire up to which interfaces, what extends what, which methods need parameters injecting and which classes should be shared (rather than a new instance created on every request).</p>
<p>Right now, it works as well as it needs to for the sample application. However it doesn&#8217;t do very well if you have more than one class that implements a given interface, and then you ask the service injector to build you a <em>blah</em> interface &#8211; in this situation it will fail. You&#8217;ll notice that although I&#8217;ve got a lot of interfaces in the sample application, they all have one class that implements the interface. I think this is a worthwhile exercise because it gets you into the mindset that you are programming <em>to</em> interface and thinking about <em>messages</em> that the objects send other objects.</p>
<h4>Pros and cons</h4>
<p>I like how my implementation creates the wiring-up configuration automatically based on the actual code. I also like how the service injector is really focussed on programming to <strong>interface</strong>: a service is simply some object that will provide a set of capabilities and the service injector&#8217;s only job is to inject these objects at run time. It does not deal with injecting strings and other configuration parameters; I think that&#8217;s OK since a string is not a <em>service</em> &#8211; and I set out to build something that would only do that job.</p>
<p>I guess that&#8217;s where my <em>service</em> injector differs from other implementations of <em>dependency</em> injection containers &#8211; I have focussed purely on something that will provide services, not any other types of depdency, such as configuration strings. Perhaps this could be considered a con!</p>
<p>The static analysis in this simple version is fairly rudimentary, although that said it will quite happily analyse the Zend framework source code. I tried this out and then made my date factory ask the service injector for a new Zend_Date object. This all worked fine &#8211; simply by changing one line of code.</p>
<h4><a name="source-code">The source code</a></h4>
<p>So I&#8217;ve written this tool purely as a way to <em>learn</em> about the ideas involved and also to see if I could find a structure that I thought was useful for <em>my</em> application. It&#8217;s been done pretty quickly but if you&#8217;d like to have a closer look you can <a tagret="_blank" href="http://svn.davegardner.me.uk/serviceinjector/trunk/">browse the source code here</a>.</p>
<h4>Other implementations for PHP</h4>
<ul>
<li>Fabien Potencier has written a <a target="_blank" href="http://components.symfony-project.org/dependency-injection/">Dependency Injection Container for the Symfony project</a>, although it will apparently work just as well as a stand-alone component</li>
<li>Benjamin Eberlei has <a target="_blank" href="http://www.whitewashing.de/blog/articles/117">written not one but two!</a></li>
<li>Federico Cargnelutti has <a target="_blank" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Di+-+Federico+Cargnelutti">proposed</a> and <a target="_blank" href="http://www.fedecarg.com/projects/show/zfdi">is working on Zend_DI</a> &#8211; a DI component for the Zend framework</li>
</ul>
<h3>Conclusions</h3>
<p>Through this process of research I have come to the following conclusions:</p>
<ul>
<li>I prefer DI over a service locator because the individual modules are <em>cleaner</em>; dependencies are passed <em>in</em> rather than the object itself going and asking for them</li>
<li>A DI framework seems the way to go, simply to reduce the complexity involved in manually creating complex object graphs</li>
<li>I like Factory classes because they serve a clear purpose and make code easy to understand</li>
<li>I want a DI framework to be able to work (almost) completely from the source code</li>
</ul>
<p>My next step is to look more closely at existing implementations to see if they could work in a production project.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2009/11/23/php-dependency-strategies-dependency-injection-and-service-locator/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Setting up continuous integration for PHP using Hudson and Phing</title>
		<link>http://www.davegardner.me.uk/blog/2009/11/09/continuous-integration-for-php-using-hudson-and-phing/</link>
		<comments>http://www.davegardner.me.uk/blog/2009/11/09/continuous-integration-for-php-using-hudson-and-phing/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 13:44:44 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Dev Environment]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ci]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[phing]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=5</guid>
		<description><![CDATA[In this, my first post, I'm going to write about the benefits of Unit Testing and how Continuous Integration (CI) can be used to get the best out of Unit Testing. This will include details of how I setup a CI system using Hudson CI server, Phing build tool combined with various other analysis tools (including PHP Unit).]]></description>
			<content:encoded><![CDATA[<p>In this, my first post, I&#8217;m going to write about the benefits of <strong>Unit Testing</strong> and how <strong>Continuous Integration</strong> (CI) can be used to get the best out of Unit Testing. This will include details of <a href="#php-ci-setup">how I setup a CI system</a> using <strong>Hudson</strong> CI server, <strong>Phing</strong> build tool combined with various other analysis tools (including <strong>PHP Unit</strong>).</p>
<p>One of the best explanations of Unit Testing I&#8217;ve read was <a href="http://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort/69263#69263" target="_blank">posted by benzado on Stack Overflow.</a></p>
<blockquote><p>Unit testing is a lot like going to the gym. You know it is good for you, all the arguments make sense, so you start working out. There&#8217;s an initial rush, which is great, but after a few days you start to wonder if it is worth the trouble.</p></blockquote>
<p>The difficulty with Unit Testing is <strong>keeping it up</strong>. It is very easy to slip into poor habits and before you know it there&#8217;s a huge chunk of code with no tests. Possibly a huge, badly designed chunk of code, that didn&#8217;t benefit from having tests written before it was coded. Before you know what&#8217;s going on, you end up with a project that you really <em>can&#8217;t</em> write tests for, because retrofitting the tests is near impossible.</p>
<p>For me, there are two critical reasons for Unit Testing:</p>
<ol>
<li><strong>Enforcing good design</strong><br />
To be able to write tests, you need to be able to zero in on a “unit” of code, isolating it from all the rest of your 1,000,000 lines of web application. Writing Unit Tests forces you to design systems that have loose coupling because otherwise it is impossible to test.</li>
<li><strong>Allowing changes to be made in confidence</strong><br />
Without Unit Tests, you get to the point where no one really wants to make any changes to the code. This is especially true in a commercial environment, where many people have worked on the code, including some key team member who has since left. Unit Tests allow you to make changes to one part of the code and be <em>pretty convinced</em> you haven&#8217;t messed up something else.</li>
</ol>
<h2>Continuous integration</h2>
<p>Martin Fowler <a href="http://martinfowler.com/articles/continuousIntegration.html" target="_blank">describes the process of Continuation Integration</a> in detail. He suggests:</p>
<blockquote><p>Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily &#8211; leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible. Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly. This article is a quick overview of Continuous Integration summarizing the technique and its current usage.</p></blockquote>
<p>The key idea behind CI is to do what is most painful often, namely “building” everyone&#8217;s code from source and making sure it all works.</p>
<p>A CI system usually consists of the following key elements:</p>
<div id="attachment_10" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-10" title="Continuous integration" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2009/11/ci-300x247.jpg" alt="Continuous integration" width="300" height="247" /><p class="wp-caption-text">Continuous integration</p></div>
<ul>
<li>Developers commit code</li>
<li>CI server detects changes</li>
<li>CI server checksout code, runs tests, analyses code</li>
<li>CI server feeds back to development team</li>
</ul>
<p>If you want to find out more about CI, I recommend the excellent book <a href="#">Continuous Integration: Improving Software Quality and Reducing Risk</a>. There is an excerpt published on <a href="http://www.javaworld.com/javaworld/jw-06-2007/jw-06-awci.html" target="_blank">JavaWorld</a> which covers a lot of the key advantages. In particular, it highlights:</p>
<blockquote><p>1. Reduce risks<br />
2. Reduce repetitive manual processes<br />
3. Generate deployable software at any time and at any place<br />
4. Enable better project visibility<br />
5. Establish greater confidence in the software product from the development team</p></blockquote>
<p>CI gets the most out of Unit Tests by <strong>forcing them to be run after every change</strong>. Not only that, but with a good CI setup, developers instantly know if they haven&#8217;t written enough tests. If avoids the situtation where Joe Bloggs has added in a huge chunk of code with zero tests.</p>
<h2 id="php-ci-setup">Setting up CI for a PHP project</h2>
<p>To get my environment setup, I consulted the following blog posts which are worth a read:</p>
<ol>
<li><a href="http://blog.jepamedia.org/2009/10/28/continuous-integration-for-php-with-hudson/" target="_blank">http://blog.jepamedia.org/2009/10/28/continuous-integration-for-php-with-hudson/</a></li>
<li><a href="http://toptopic.wordpress.com/2009/02/26/php-and-hudson/" target="_blank">http://toptopic.wordpress.com/2009/02/26/php-and-hudson/</a></li>
</ol>
<p>I&#8217;m assuming you&#8217;re using a CentOS 5 server (or I guess RHEL5). If not, you may still find various parts of this useful.</p>
<h3>1. Install JDK</h3>
<p>EPEL provide a set of CentOS packages, including a package for openJDK. This is the easiest way of installing Java.</p>
<p>Firstly, setup <a href="http://fedoraproject.org/wiki/EPEL/FAQ#howtouse" target="_blank">EPEL</a>:</p>
<pre class="code">wget -O /etc/yum.repos.d/hudson.repo http://hudson-ci.org/redhat/hudson.repo</pre>
<p>Next install <a href="http://openjdk.java.net/install/" target="_blank">OpenJDK</a>:</p>
<pre class="code">yum install java-1.6.0-openjdk</pre>
<h3>2. Install Hudson</h3>
<p>Download and install the CentOS RPM for <a href="http://hudson-ci.org/redhat/" target="_blank">Hudson</a>:</p>
<pre class="code">wget -O /etc/yum.repos.d/hudson.repo http://hudson-ci.org/redhat/hudson.repo
rpm --import http://hudson-ci.org/redhat/hudson-ci.org.key
yum install hudson</pre>
<p>Now Hudson is installed, we can start using the standard CentOS “service” command.</p>
<pre class="code">service hudson start</pre>
<p>We can check Hudson is working by pointing the browser at port 8080 (the default Hudson port). Hudson will work “out of the box”  and give you a web interface immediately. This is the primary reason I decided to go with Hudson over the other possibilities, eg: CruiseControl and phpUnderControl. Although I didn&#8217;t do an exhaustive analysis before I decided on Hudson, it just <em>seemed</em> right to me.</p>
<p>To get the graphing engine working for Hudson, you may need to install x.</p>
<pre class="code">yum groupinstall base-x</pre>
<h3>3. Install phing</h3>
<p><a href="http://phing.info/trac/" target="_blank">Phing</a> is a PHP project build system or build tool based on Apache Ant. A build tool ensures that the process of creating your working web application from source code happens in a structured and repeatable way. This helps reduce the possibility of errors caused by simply uploading files via FTP or some other simple method.</p>
<p>Make sure PEAR is installed for PHP (this is the easiest way of installing phing):</p>
<pre class="code">yum install php-pear</pre>
<p>Then install the PEAR phing package:</p>
<pre class="code">pear channel-discover pear.phing.info
pear install phing/phing</pre>
<h3>4. Setup SVN</h3>
<p>If you haven&#8217;t got a <a href="http://subversion.tigris.org/" target="_blank">Subversion</a> repository, you&#8217;re going to need one (or some other SCM tool like CVS, GIT or Mercurial).</p>
<pre class="code">yum install mod_dav_svn</pre>
<p>The simplest setup involves creating a repo in /var/www/svn/&lt;my repo&gt;</p>
<pre class="code">mkdir -v /var/www/svn/test
svnadmin create --fs-type fsfs /var/www/svn/test
chown –R apache:apache /var/www/svn/test</pre>
<p>Setup Apache by pretty much uncommenting the lines in /etc/httpd/conf.d/subversion.conf. Once Apache restarted, you&#8217;ll be able to get to it via /repos/test, assuming you&#8217;re using the default settings (sets up SVN on /repos). I haven&#8217;t gone into the details of getting SVN up and running; there are lots of resources out there that will help you do this.</p>
<h3>5. Install PHP tools</h3>
<h5><a href="http://www.phpdoc.org/" target="_blank">PHPDocumentor</a> – to generate documentation automatically from code</h5>
<pre class="code">pear install PhpDocumentor</pre>
<h5><a href="http://github.com/sebastianbergmann/phpcpd" target="_blank">PHP CPD</a> – “copy and paste detector” for PHP</h5>
<p>This requires PHP 5.2. At time of writing, this wasn&#8217;t standard with CentOS 5, but is part of the CentOS “test” repo. This can be setup by creating a yum repo file, eg: /etc/yum.repos.d/centos-test.repo and populating with:</p>
<pre class="code">[c5-testing]
name=CentOS-5 Testing
baseurl=http://dev.centos.org/centos/5/testing/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing</pre>
<p>Then you can do:</p>
<pre class="code">yum update php</pre>
<p>You may also need to upgrade pear; if the install of phpcpd fails (below). To do this, try:</p>
<pre class="code">pear upgrade pear</pre>
<p>or, if this wants to be forced, and you think it&#8217;s a good idea (I did):</p>
<pre class="code">pear upgrade --force pear</pre>
<p>Finally we can install phpcpd!</p>
<pre class="code">pear channel-discover pear.phpunit.de
pear install phpunit/phpcpd</pre>
<h5><a href="http://www.pdepend.org/news.html" target="_blank">PHP Depend</a> &#8211; help analyse quality of codebase</h5>
<p>Note you may have update PHP to include the DOM module (first line below).</p>
<pre class="code">yum install php-dom
pear channel-discover pear.pdepend.org
pear install pdepend/PHP_Depend-beta</pre>
<h5><a href="http://pear.php.net/package/PHP_CodeSniffer" target="_blank">PHP Code Sniffer</a> &#8211; analyse code for adherence to style/standards</h5>
<pre class="code">pear install PHP_CodeSniffer-1.2.0</pre>
<h5><a href="http://pear.php.net/package/PHP_CodeSniffer" target="_blank">PHP Unit</a> &#8211; unit test framework for PHP</h5>
<pre class="code">pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit</pre>
<p>To make PHP Unit work, we need <a href="http://xdebug.org/" target="_blank">XDebug</a> installed, the PHP profiler.</p>
<pre class="code">yum install php-devel gcc
pecl install xdebug</pre>
<h3>6. Install Hudson plugins</h3>
<p>Use the web interface to install the following plugins (Manage Hudson -&gt; Plugins).</p>
<ul>
<li>Checkstyle</li>
<li>Clover</li>
<li>DRY</li>
<li>Green Balls (handy because it shows successful builds as green circles rather than blue)</li>
<li>JDepend</li>
<li>xUnit (will handle the output of PHPUnit test results XML)</li>
</ul>
<h3>7. Setup the phing build script</h3>
<p>The Phing build script defines what steps will be taken to “build” the application.</p>
<p>Hudson itself works by placing our code into a project workspace. It will checkout the code from subversion and place it into the following location, where “Test” is the name of our project.</p>
<pre class="code">/var/lib/hudson/jobs/Test/workspace/</pre>
<p>We can then use the Phing build script to carry out a number of processes on this code. When we talk about “building”, what we will actually do is place the code where we need it so it can actually run the website (we&#8217;ll keep this within the workspace) plus we run tests etc&#8230;</p>
<p>We&#8217;ll keep the build script in the subversion repository, so effectively it will be updated from SVN each build. For this approach to work, the following XML needs to be stored in a file named build.xml, stored in the project root folder (within trunk), eg: /trunk/build.xml</p>
<pre class="code">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
 &lt;project name="test" basedir="." default="app"&gt;
    &lt;property name="builddir" value="${ws}/build" /&gt;

    &lt;target name="clean"&gt;
        &lt;echo msg="Clean..." /&gt;
        &lt;delete dir="${builddir}" /&gt;
    &lt;/target&gt;

    &lt;target name="prepare"&gt;
        &lt;echo msg="Prepare..." /&gt;
        &lt;mkdir dir="${builddir}" /&gt;
        &lt;mkdir dir="${builddir}/logs" /&gt;
        &lt;mkdir dir="${builddir}/logs/coverage" /&gt;
        &lt;mkdir dir="${builddir}/docs" /&gt;
        &lt;mkdir dir="${builddir}/app" /&gt;
    &lt;/target&gt;

    &lt;!-- Deploy app --&gt;
    &lt;target name="app"&gt;
        &lt;echo msg="We do nothing yet!" /&gt;
    &lt;/target&gt;

    &lt;!-- PHP API Documentation --&gt;
    &lt;target name="phpdoc"&gt;
        &lt;echo msg="PHP Documentor..." /&gt;
        &lt;phpdoc title="API Documentation"
                destdir="${builddir}/docs"
                sourcecode="yes"
                defaultpackagename="MHTest"
                output="HTML:Smarty:PHP"&gt;
            &lt;fileset dir="./app"&gt;
                &lt;include name="**/*.php" /&gt;
            &lt;/fileset&gt;
        &lt;/phpdoc&gt;
    &lt;/target&gt;

    &lt;!-- PHP copy/paste analysis --&gt;
    &lt;target name="phpcpd"&gt;
        &lt;echo msg="PHP Copy/Paste..." /&gt;
        &lt;exec command="phpcpd --log-pmd=${builddir}/logs/pmd.xml source" escape="false" /&gt;
    &lt;/target&gt;

    &lt;!-- PHP dependency checker --&gt;
    &lt;target name="pdepend"&gt;
        &lt;echo msg="PHP Depend..." /&gt;
        &lt;exec command="pdepend --jdepend-xml=${builddir}/logs/jdepend.xml ${ws}/source" escape="false" /&gt;
    &lt;/target&gt;

    &lt;!-- PHP CodeSniffer --&gt;
    &lt;target name="phpcs"&gt;
        &lt;echo msg="PHP CodeSniffer..." /&gt;
        &lt;exec command="phpcs --standard=ZEND --report=checkstyle ${ws}/source &gt; ${builddir}/logs/checkstyle.xml" escape="false" /&gt;
    &lt;/target&gt;

    &lt;!-- Unit Tests &amp; coverage analysis --&gt;
    &lt;target name="phpunit"&gt;
        &lt;echo msg="PHP Unit..." /&gt;
        &lt;exec command="phpunit --log-junit ${builddir}/logs/phpunit.xml --log-pmd ${builddir}/logs/phpunit.pmd.xml --coverage-clover ${builddir}/logs/coverage/clover.xml --coverage-html ${builddir}/logs/coverage/ ${ws}/source/tests"/&gt;
    &lt;/target&gt;
&lt;/project&gt;</pre>
<h3>8. Setup Hudson</h3>
<p>The first step is to create a new job.</p>
<ul>
<li>From the Hudson homepage, click New Job.</li>
<li>Enter a Job name, for example “Dave&#8217;s Product Build” and choose “Build a free-style software project”. Click OK.</li>
</ul>
<p>Now you need to configure the job; the configuration form should be displayed immidiately after adding.</p>
<p>Under <strong>Source Code Management</strong> choose <strong>Subversion</strong> and enter:</p>
<ul>
<li>Repository URL: http://www.myrepo.com/path/to/repo</li>
<li>Local module directory: source</li>
<li>Check &#8220;Use update&#8221; which speeds up checkout</li>
</ul>
<p>Under <strong>Build Triggers</strong> select <strong>Poll SCM</strong> and enter the following schedule:</p>
<pre class="code">5 * * * *
10 * * * *
15 * * * *
20 * * * *
25 * * * *
30 * * * *
35 * * * *
40 * * * *
45 * * * *
50 * * * *
55 * * * *</pre>
<p>Note that this will poll for changes to the repository every 5 minutes and rebuild if any changes are detected.</p>
<p>Under <strong>Build</strong> click the button to <strong>Add build step</strong> and choose <strong>Execute shell</strong>, enter the command:</p>
<pre class="code">phing -f $WORKSPACE/source/build.xml prepare app phpdoc phpcs phpunit -Dws=$WORKSPACE</pre>
<p>Under <strong>Post-build Actions</strong> choose:</p>
<ul>
<li>Check Publish Javadoc and then enter:<br />
Javadoc directory = build/docs/</li>
<li>Check Publish testing tools result report and then click Add and pick PHP Unit, enter:<br />
+ PHPUnit Pattern = build/logs/phpunit.xml</li>
<li>Check Publish Clover Coverage Report and enter:<br />
+ Clover report directory = build/logs/coverage<br />
+ Clover report file name = clover.xml</li>
<li>Check Publish duplicate code analysis results and enter:<br />
+ Duplicate code results = build/logs/phpunit.pmd-cpd.xml</li>
<li>Check Publish Checkstyle analysis results and enter:<br />
+ Checkstyle results = build/logs/checkstyle.xml</li>
</ul>
<p>Finally, click <strong>Build Now</strong> to test it all works.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2009/11/09/continuous-integration-for-php-using-hudson-and-phing/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>
