<?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>Wed, 27 Jul 2011 15:14:29 +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>A mapper pattern for PHP</title>
		<link>http://www.davegardner.me.uk/blog/2011/07/27/a-mapper-pattern-for-php/</link>
		<comments>http://www.davegardner.me.uk/blog/2011/07/27/a-mapper-pattern-for-php/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 15:14:29 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[data mapper]]></category>
		<category><![CDATA[mapper]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[serialisation]]></category>
		<category><![CDATA[web service]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=209</guid>
		<description><![CDATA[Introducing a pattern for flexible mapping between domain objects and representations (and vice-versa) using PHP.]]></description>
			<content:encoded><![CDATA[<p>The “mapper” pattern allows us to either:</p>
<ul>
<li><a href="#object_to_representation_mapper">create a representation of an object graph</a></li>
<li><a href="#representation_to_object_mapper">create an object graph from a representation</a></li>
</ul>
<p>This sounds very much like straight-forward <a href="http://en.wikipedia.org/wiki/Serialization" target="_blank">serialisation</a>, but there are some key differences.</p>
<ol>
<li><strong>It is not necessarily two-way</strong><br />
It is possible to map from an object graph to a representation that does not contain all the information to reconstruct an object graph. An example might be a case where we map a user&#8217;s &#8220;screen name&#8221; out of the user object; a useful piece of information, but not enough to construct a fully-formed user object on its own.</li>
<li><strong>The representation is flexible</strong><br />
It is possible to write mappers that map to and from various different representation formats (eg: JSON, XML, <a href="http://wiki.apache.org/cassandra/API#batch_mutate" target="_blank">Cassandra Mutation Map</a>). PHP&#8217;s in-built <a href="http://www.php.net/manual/en/function.serialize.php" target="_blank">serialisation</a> has a fixed end-result, determined by the PHP engine itself.</li>
<li><strong>There are a number of added-extras</strong><br />
These include in-built caching, the ability to override values and provide defaults. More on this later.</li>
</ol>
<h3>How they fit into the overall architecture</h3>
<p>I&#8217;m a huge fan of <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">Domain Driven Design</a>. When implementing a new set of functionality, I usually start with <a href="http://en.wikipedia.org/wiki/Class-responsibility-collaboration_card" target="_blank">CRC cards</a>, formulate a design for the domain objects and then start on prototyping in conjunction with unit testing. Aside &#8211; I generally don&#8217;t practice Test Driven Development, although I will hopefully try it out at some point.</p>
<p>The mappers come into play when creating representations of domain objects or creating an object graph from representations.</p>
<div id="attachment_213" class="wp-caption aligncenter" style="width: 610px"><a href="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/07/mappers.jpg"><img class="size-full wp-image-213 " src="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/07/mappers.jpg" alt="How mappers can be used in overall architecture" width="600" height="98" /></a><p class="wp-caption-text">How mappers can be used in overall architecture</p></div>
<h4>Web Service</h4>
<p><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" target="_blank">RESTful Web Service</a> <a href="http://en.wikipedia.org/wiki/GET_%28HTTP%29#Request_methods" target="_blank">GET</a> requests can be created by mapping domain object graphs to representations (JSON, XML, HTML). The schema (more on this later) allows intricate control over exactly which bits of the domain object graph are mapped, allowing for a variety of different representations of the same domain objects. I&#8217;m ignoring <a href="http://en.wikipedia.org/wiki/HATEOAS" target="_blank">HATEOS</a> for the purposes of this post, this can easily be added.</p>
<p>RESTful Web Service <a href="http://en.wikipedia.org/wiki/POST_%28HTTP%29" target="_blank">POST</a> and <a href="http://en.wikipedia.org/wiki/PUT_%28HTTP%29#Request_methods" target="_blank">PUT</a> requests can be handled by mapping the POSTed or PUT representations into a domain object graph and then saving these via the persistence layer.</p>
<h4>Persistence</h4>
<p>Retrieving domain objects from a persistence service (loading) can be facilitated by the representation to object mapper. One example of a specific implementation is a <a href="http://wiki.apache.org/cassandra/API#batch_mutate" target="_blank">Cassandra Mutation Map</a> (a representation) to object mapper.</p>
<p>Persisting domain objects (saving) can be facilitated by the object to representation mapper, for example mapping to a Cassandra Mutation Map or SQL.</p>
<h2>Building blocks of the domain layer</h2>
<p>There are many ways that this mapper pattern could be implemented. The implementation I have created relies on a number of consistent design principles within the domain layer. The important building blocks are outlined below.</p>
<h3>Keyed objects, value objects, collection objects</h3>
<p>We can construct our domain object based around three core object types. Any concrete domain objects therefore share functionality of one of these types and implement a common interface.</p>
<ul>
<li><strong>Keyed objects</strong><br />
Domain objects that have a uniquely identifiable key &#8211; globally unique within the application. These objects are stored in an Identity Map to make sure only one instance for each unique key value is ever created.</li>
<li><strong>Value objects</strong><br />
Domain objects that do not have a uniquely identifiable key. These objects cannot be stored in an Identity Map, nor would it make sense to do so.</li>
<li><strong>Collections</strong><br />
Domain objects that represent a list of other objects. These, at their most basic level, implement the Iterator interface. Each different type of domain object will have its own accompanying collection object.</li>
</ul>
<h3>Virtual-proxy pattern for lazy-loading</h3>
<p>All keyed domain objects can be replaced with a <a href="http://en.wikipedia.org/wiki/Lazy_loading#Virtual_proxy" target="_blank">virtual-proxy</a>. This behaves like the original object (implements the same interface) but only loads itself from the database at the last minute when needed.</p>
<h3>Getters</h3>
<p>All objects have a consistently named “getter” defined. I used to think this was a <a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html" target="_blank">bad idea</a> but I have since mellowed in my opinion (setters are still evil).</p>
<h2 id="object_to_representation_mapper">Object to representation mapper</h2>
<p>The aim here is to turn an object graph into a representation. An example:</p>
<pre class="code">
class user {
    public function getUsername();
    public function getName();
    public function getRegisteredTimestamp();
}
</pre>
<p>We then map this to a JSON representation using the schema:</p>
<pre class="code">$schema = array(
    'username',
    'name',
    'registeredTimestamp'
    );</pre>
<p>Resulting in:</p>
<pre class="code">{"username":"davegardnerisme","name":"Dave Gardner","registeredTimestamp":1284850800}</pre>
<h3>Schemas</h3>
<p>Object graphs nearly always have great complexity, often involving circular relationships. When mapping to representations we often don&#8217;t want all this complexity, nor would it be feasible to include it all! With a rich domain layer built up from many contained lazy-loading objects, if you continue to dig down into the object graph you could end up loading every single object that exists within your application!</p>
<p>This is why we use schemas when mapping from objects to representations &#8211; we need to choose <strong>what</strong> to actually map. What we are really doing it identifying how far to dip into the object graph when formulating the representation.</p>
<h3>How it works</h3>
<p>The implementation of the object-to-representation concept has a number of key elements:</p>
<ol>
<li><strong>Object graph walker</strong><br />
Aware of how to walk through the object graph, according to the given schema, drilling into any contained objects and collections.</li>
<li><strong>Object property extractor</strong><br />
Able to extract a property from an object according to a schema.</li>
<li><strong>Property to value convertor</strong><br />
Able to turn a retrieved property into a scalar value (string/integer/float).</li>
</ol>
<h3>Pseudo code</h3>
<p>We run this code passing in the object to map from plus the schema. The code is structured to be run recursively, building the output array (passed by reference) as it goes.</p>
<pre class="code">foreach (entry in schema)
{
    if (schema entry indicates we should map to a list)
    {
        assert (we have a list)
        foreach (item in list)
        {
            call this recursively with this item and the sub-selection of schema
        }
    }
    else
    {
        extract property of object according to the schema
        convert this property to a scalar value
        add this property to the mapped-to data
    }
}</pre>
<h3>Caching</h3>
<p>One interesting thing about the object to representation cache is that you can add in a caching layer which avoids, in many cases, the need to actually carry out the mapping. This is particularly effective when complex object graphs built from immutable objects. The reason is that we don&#8217;t actually need to load the objects themselves from the database; we can use the virtual-proxy key to give us a cache key and then simply load the representation directly. With PHP it&#8217;s usually a good idea to use APC to cache representations (over Memcached) to avoid the 1MB limit. This makes it more effective when mapping/caching large object graphs to large representations.</p>
<p>A caching system can be added into the mapping code:</p>
<pre class="code">if (object to map is a keyed object)
{
    cache key = hash on (schema + object key)
    if (!exists in cache)
    {
        map as normal
    }
    else
    {
        return the cached representation
    }
}</pre>
<h3>Object verification</h3>
<p>The domain layer is built upon the principle of lazy-loading, making use of the virtual-proxy pattern. These virtual-proxies will initialise a concrete object <strong>when they need to</strong>. Remember that a virtual-proxy has a property that indicates some kind of unique identifier for the object, and it knows how to load itself. Therefore when mapping, if we need to turn a virtual-proxy object into a single value, we don&#8217;t need to load it, since we already have the unique identifier. This is a nice optimisation. However, this is not always desirable.</p>
<p>Sometimes you want to guarantee that objects exist, by forcing any objects touched via the mapper to be loaded from the database. This is where the verification feature comes in.</p>
<h3>Overrides</h3>
<p>We can tweak the final representation by adding overrides. These are a way of saying &#8220;please ignore any value that could be extracted from the object and use this object/callback instead&#8221;. One interesting way I have used these is to attach URL properties to domain objects. URLs are a property that does not usually belong in the problem domain, but rather are concerned with a specific representation scheme &#8211; HTTP. Therefore the overrides can be added within the web service layer to allow us to map a URL for a domain object within a specific context. One interesting point to note, required by the URL example, is that the override doesn&#8217;t actually have to override anything. The original object does not necessarily have to have this property in the first place.</p>
<h3>Example</h3>
<p>All these examples use the domain objects from my <a href="http://www.davegardner.me.uk/experience/glastofinder/">GlastoFinder</a> project. You can <a href="#glastofinder_object_reference">check out the interfaces for these</a> in the last section of this post.</p>
<h4>Mapping the list of places to JSON representation</h4>
<pre class="code">$schema = array(
    service_mapper::LOOP_ITEMS =&gt; array(
        'key',
        'title',
        'category' =&gt; array(
            'key',
            'title'
            ),
        'location' =&gt; array(
            'latitude',
            'longitude'
            ),
        'icon',
        'hashTag',
        'details'
        )
    );
$mapper = $this-&gt;diContainer-&gt;getInstance(
        'service_mapper_objectToArray',
        $schema
        );
$json = $mapper-&gt;map($list);</pre>
<p>Sample output:</p>
<pre class="code">[
    {
        "key": "0f45b80d-96d5-546d-bade-c2e583489783",
        "title": "Poetry &amp; Words",
        "category": {
            "key": "other_venues",
            "title": "Other Venues"
        },
        "location": {
            "latitude": 51.149364968572,
            "longitude": -2.5799948897032
        },
        "icon": "/i/otherstage-sm.png",
        "hashTag": "poetryandwords",
        "details": null
    },
    {
        "key": "10b11ab0-e164-5ac7-8ea4-ea5670cdf54e",
        "title": "Pedestrian Gate E",
        "category": {
            "key": "gates",
            "title": "Gates"
        },
        "location": {
            "latitude": 51.147641084707,
            "longitude": -2.6001275707455
        },
        "icon": "/i/gate-sm.png",
        "hashTag": "gatee",
        "details": null
    }
]</pre>
<h2 id="representation_to_object_mapper">Representation to object mapper</h2>
<p>This is the complete opposite of the object to representation mapper. We take some representation and then turn this into an object graph; potentially constructed of many related objects. An example:</p>
<p>Representation:</p>
<pre class="code">{"username":"davegardnerisme","name":"Dave Gardner","registeredTimestamp":1284850800}</pre>
<p>Will be able to yield us a user object with the following properties:</p>
<pre class="code">class user {
/**
 * Constructor
 *
 * @param string $username The user's username - an alphanumeric (a-zA-Z0-9) string, unique
 * @param string $name The user's full name, forename plus surname, or however they want to name themselves
 * @param integer $registeredTimestamp The date this user was registered
 */
public function __construct(
    $username,
    $name,
    $registeredTimestamp
    )
}</pre>
<p>The mapper, when asked to construct a user object, will examine the values needed by the object (by looking at its constructor) and then extract these properties from the representation. Unlike the object to representation mapper, no schema is needed. The schema is inherent in the object definitions themselves.</p>
<h3>How it works</h3>
<p>The implementation of the representation-to-object concept has a number of key elements:</p>
<ol>
<li><strong>Code analysis tool</strong><br />
Ideally a static analysis tool to avoid the cost of reflection. This would know what parameters are needed to construct each domain object.</li>
<li><strong>Recursive object-building code</strong><br />
Able to determine what type of thing to build (depends on what value available in the representation) and then build it.</li>
</ol>
<h3>Pseudo code</h3>
<p>We run this code passing in the object to map from plus the schema. The code is structured to be run recursively, building the output array (passed by reference) as it goes.</p>
<pre class="code">decide which value to use by looking at representation, defaults and overrides
if (value to use is a scalar [string, int, float])
{
    build placeholder domain object
}
else
{
    build full domain object
}

if (thing to build is list)
{
    foreach (item within representation)
    {
        call function recursively to build item, then add to list
    }
}

verify all built objects, if required</pre>
<h3>Overrides and defaults</h3>
<p>When we map from a representation to an object, it&#8217;s often useful to be able to tweak the process, supplying default values where necessary and overrides in certain situations. To understand a use-case, it&#8217;s important to understand the principle of “fully formed objects”. This means that whenever we create an object, we always supply every piece of information to the object constructor, meaning that if ever we have an object instance, we know that all the data is present and correct. So for example a user object may have a createdTimestamp; this should be supplied, as a valid value, whenever we construct the object. To adhere to this, we could not pass in a NULL value and leave it to the object to provide a default value (eg: now). Instead we should use a Factory for this, or we could use a mapper default!</p>
<p>If we had a web service end point that created a new user, we may require a representation (eg: JSON) to be PUT. However what about the createdTimestamp? Should this be in the PUT representation? My thinking is that no, it shouldn&#8217;t. Instead we use the mapper override feature to <strong>force</strong> the createdTimestamp to be exactly the time that the user was created, according to the server processing the request.</p>
<p>The following illustrates defining an override callback to force a createdTimestamp to be defined at time of mapping. This makes use of <a href="http://php.net/manual/en/functions.anonymous.php" target="_blank">PHP 5.3 anonymous functions</a>.</p>
<pre class="code">$mapper = $diContainer-&gt;getInstance('service_mapper_jsonToObject');
$mapper-&gt;addOverride(
    array('createdTimestamp'),
    function () { return time(); }
    );</pre>
<h3>Rules for building domain objects</h3>
<h4>Placeholders (virtual-proxy) vs full domain objects</h4>
<p>The mapping algorithm ultimately boils down to a situation where we need to build some object, based on some value. This value could be a scalar (string, integer, float) or an array. We need some rules to determine how we go about building a domain object based on the situation we find, specifically what type of value we have.</p>
<ul>
<li><strong>Scalar &#8211; string, integer or float</strong><br />
When we are asked to build a domain object and we find a scalar in the representation, we make the assumption that this value refers to some unique identifier for the object and therefore build a placeholder object (virtual-proxy) instead.</li>
<li><strong>Associative array</strong><br />
When we are asked to build a domain object and we are presented with an array of values, we make the assumption that all of the necessary constructor properties are present in the representation. We then dig through these values and match them up with constructor arguments, before finally constructing the fully-formed domain object.</li>
</ul>
<h4>Collections &#8211; recursion</h4>
<p>Whenever we are building a collection object, we look for a numerically-indexed array of items within the representation. We then call the “turn a value into a domain object” method recursively to yield us objects to push onto our list. The assumptions here are that collections are always represented as an Iterable object within the domain layer.</p>
<h3>Verification</h3>
<p>When we carry out the mapping, we may create any number of placeholder (virtual-proxy) objects in place of real domain objects. These will then be lazy-loaded on-demand. This is all fine and good, but not if you want to ensure that all the objects are valid. Luckily it is trivial for the mapper to keep track of any placeholders it mints during its mapping job. With the verification flag set, this list of of placeholders can then be force-loaded to ensure that they actually exist. Whether or not this is desirable depends on the situation; when accepting PUT or POSTed representations via a web service the safety net is useful, when mapping from a database representation we often don&#8217;t want the overhead.</p>
<h2 id="glastofinder_object_reference">GlastoFinder domain object reference</h2>
<h4>Location interface</h4>
<pre class="code">interface domain_location_interface
{
    /**
     * Get latitude
     *
     * @return float
     */
    public function getLatitude();

    /**
     * Get longitude
     *
     * @return float
     */
    public function getLongitude();

    /**
     * Get distance to another location
     *
     * Uses "haversine" formula
     * @see http://www.movable-type.co.uk/scripts/latlong.html
     *
     * @param mz_domain_location $otherLocation The other location
     *
     * @return float The distance measured in kilometres
     */
    public function getDistanceTo(mz_domain_location $otherLocation);
}</pre>
<h4>Place interface</h4>
<pre class="code">interface domain_place_interface
        extends     domain_keyed_interface,
                    domain_hasLocation_interface
{
    /**
     * Get title
     *
     * @return string
     */
    public function getTitle();

    /**
     * Get category
     *
     * @return domain_place_category_interface
     */
    public function getCategory();

    /**
     * Get icon
     *
     * @return string
     */
    public function getIcon();

    /**
     * Get hash tag
     *
     * @return domain_hashTag_interface
     */
    public function getHashTag();

    /**
     * Get details
     *
     * @return string
     */
    public function getDetails();
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2011/07/27/a-mapper-pattern-for-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>GlastoFinder &#8211; writing a mobile application</title>
		<link>http://www.davegardner.me.uk/blog/2011/07/25/glastofinder-writing-a-mobile-application/</link>
		<comments>http://www.davegardner.me.uk/blog/2011/07/25/glastofinder-writing-a-mobile-application/#comments</comments>
		<pubDate>Mon, 25 Jul 2011 16:56:18 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[geolocation]]></category>
		<category><![CDATA[glastofinder]]></category>
		<category><![CDATA[glastonbury]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=189</guid>
		<description><![CDATA[Have you ever been to Glastonbury? It's massive. Seriously huge. This is a fantastic feature - there's loads to do and you can wonder aimlessly for hours and hours. However! If you're trying to find your friends it's a problem. Figuring out where everyone is can be tricky. The solution, to a web technologist like myself, was obvious - build a website! As they say, when all you have is a hammer… And so GlastoFinder was born.]]></description>
			<content:encoded><![CDATA[<p>Have you ever been to Glastonbury? It&#8217;s massive. Seriously huge. This is a fantastic feature &#8211; there&#8217;s loads to do and you can wander aimlessly for hours and hours. However! If you&#8217;re trying to find your friends it&#8217;s a problem. Figuring out where everyone is can be tricky.</p>
<p>The solution, to a web technologist like myself, was obvious &#8211; build a website! As they say, when all you have is a hammer… And so <a href="http://www.davegardner.me.uk/experience/glastofinder/">GlastoFinder</a> was born.</p>
<p style="text-align: center;"><a href="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/07/P1110132.JPG"><img class="size-large wp-image-190   aligncenter" title="Looking down on Glastonbury" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/07/P1110132-1024x439.jpg" alt="Looking down on Glastonbury" width="590" /></a></p>
<h2>Interesting features of the build</h2>
<p>This project was completed quickly. It leaned on a ton of features and patterns I have been developing over a number of years, plus some new tricks (EC2)!</p>
<h3>EC2</h3>
<p>This was my first personal project that made use of <a href="http://aws.amazon.com/ec2/" target="_blank">Amazon&#8217;s Elastic Compute Cloud (EC2)</a>. The process felt good. I created an instance and then did (roughly) this:</p>
<pre class="code">svn co http://svn.davegardner.me.uk/path/to/repo glastofinder_com
cd glastofinder_com
./scripts/install-build-dependencies
phing build</pre>
<p>This feels good. Everything is scripted. Once I finished with the project, I simply shut down the instance. This makes use of the <a href="http://www.phing.info/trac/" target="_blank">Phing</a> build tool, <a href="http://www.davegardner.me.uk/blog/2009/11/09/continuous-integration-for-php-using-hudson-and-phing/">which is mentioned in one of my previous posts</a>.</p>
<h3>Building on top of Twitter</h3>
<p>This is the first time I&#8217;ve built an application on top of Twitter. What I mean by that is that the application relies on Twitter to operate and to supply some of its features (Tweet-to-check-in). My experience is broadly positive. Leveraging an existing network removes the need to build boring sign up, sign in and “follow” functionality. My only grumble is that I think the Twitter API could be less restrictive.</p>
<h3>Using jQuery mobile for the frontend</h3>
<p>This was picked at the last minute to get a vaguely professional frontend in a short amount of time. Whether it achieved this lofty goal is up for debate.</p>
<h3>Solid architecture principles</h3>
<p>The backend (PHP) makes use of a number of nice patterns that are worth a mention.</p>
<ul>
<li>Layered architecture &#8211; web service, domain, DAO, service</li>
<li><a href="http://www.davegardner.me.uk/blog/2009/11/23/php-dependency-strategies-dependency-injection-and-service-locator/">Dependency Injection container</a></li>
<li><a href="http://www.davegardner.me.uk/blog/tag/lazy-load/">Lazy-loading (virtual proxy) pattern</a> for domain objects</li>
<li>Strong OO principles including using <a href="http://www.davegardner.me.uk/blog/2011/03/04/mocking-iterator-with-phpunit/">iterator</a> objects for collections</li>
<li>Mapping pattern (blog post to follow on this)</li>
</ul>
<p>In particular, the interplay between a <strong>strong and pure domain layer</strong>, the use of <strong>Data Access Objects (DAOs)</strong> for persistence and the <strong>mapper pattern</strong> to generate Web Service representations worked very well indeed.</p>
<h2>Field testing</h2>
<p>There&#8217;s nothing like a baptism of fire. I discovered at 10pm on the Tuesday before Glastonbury (I had to leave my house at 7am the next morning) that Twitter search did not include results from new users (most of my friends). There was much last-minute hackery to implement a workaround. Testing is always an important activity. Mimicking the conditions that the application should operate under is especially important to ensure things worth smoothly “in the field”.</p>
<p>I would say that overall the app worked “acceptably”. There were a lot of lessons learned from actually being at the festival!</p>
<h3>Things that were a problem</h3>
<ul>
<li><strong>Patchy network</strong><br/>This probably had the biggest impact. The network was not unusable, merely patchy and often slow. This meant that the more advanced features (Google Map) were much less useful than the light-weight features (timeline / check-in via Twitter).</li>
<li><strong>Setup process difficult</strong><br/>We didn&#8217;t invest an enormous amount of energy trying to make this smooth. The idea was that you would choose which of your Twitter friends could track your location. This avoided a blanket approach but was fiddly to setup and the UX was less than obvious.</li>
<li><strong>Twitter search is heavy cruft</strong><br/>It&#8217;s not possible to build an app that relies on Twitter search. You are not guaranteed to get a message appearing in Twitter search and new users will be absent completely for a few days. Therefore you cannot simply sign-up to the app as a new user and start using it straight away. This would be a massive problem. There are other issues with Twitter search <a href="http://code.google.com/p/twitter-api/issues/detail?id=214" target="_blank">like the fact that the from_user_id is not actually a valid Twitter user ID.</a></li>
</ul>
<h3>Things that worked well</h3>
<ul>
<li><strong>Timeline</strong><br/>The timeline view was great. Firstly because you could see quickly both where people were and also who was actively using the app. Secondly because of the amount of information crammed into each entry (where someone was, when, where they were heading off to, what they were up to). Thirdly because it was fast!</li>
<li><strong>Check-in and check-out via Twitter</strong><br/>Despite the failings of Twitter search, this still turned out to be an amazing feature. It was super fast to check-in via Twitter at one of the many hash-tagged venues &#8211; especially at busy times when 3G didn&#8217;t work (Tweet via SMS).</li>
</ul>
<h3>Potential improvements</h3>
<ul>
<li><strong>Crowd-sourced locations</strong><br/>Each Glastonbury things popup that you don&#8217;t know about before. Epic food stalls setup shop and become instant favourites (<a href="http://bookhams.com/cheese-on-toast/" target="_blank">like the cheese on toast stand</a>). Allowing users to add and share places would be a good addition.</li>
<li><strong>Use DataSift!</strong><br/>I know these guys from <a href="http://meetup.com/Cassandra-London" target="_blank">Cassandra London</a> and <a href="http://datasift.net/a/platform/" target="_blank">their product efficiently processes the Twitter “firehose”</a>. Using this instead of the Twitter search API would save lots of effort.</li>
<li><strong>Build a native app</strong><br/>This is something I was against when I started the project. However a native app would have a few key advantages over a website-based implementation. The major advantage would be that the map could be cached within the app itself, making it much more usable at the festival. This would not be without its drawbacks. The current implementation (based around Google Maps) lends itself to scalability &#8211; it would be relatively simple to add lots of other events, simply using Google Maps and crowd-sourced locations database.</li>
</ul>
<h2>The results</h2>
<p>I decided to analyse my movements at the festival based on my check-ins and check-outs. As a starter for 10, I&#8217;ve just pulled out all the check-ins by day. If I get time I&#8217;ll mash this up with a map so you can see how much ground I&#8217;ve covered and/or if the geo-location was accurate!</p>
<h4>Wednesday</h4>
<ul>
<li><strong>It&#8217;s 6:59 and the computer is going off now. Leaving the house in ~ 40 minutes. Any bugs are now classified as &quot;features&quot;.</strong> <span style="color:#555;">159km from the festival at 7:00am</span>
</li>
<li><strong>At Waterloo!</strong> <span style="color:#555;">176km from the festival at 8:30am</span>
</li>
<li><strong>Slow progress. </strong> <span style="color:#555;">171km from the festival at 10:29am</span>
</li>
<li><strong>Services!</strong> <span style="color:#555;">85km from the festival at 11:45am</span>
</li>
<li><strong>Holy moly I&#8217;m getting near. Last 3G signal?</strong> <span style="color:#555;">44km from the festival at 1:07pm</span>
</li>
<li><strong>Frome now. The end is in sight. And it has a huge black cloud over it. </strong> <span style="color:#555;">25km from the festival at 1:41pm</span>
</li>
<li><strong>Epic queues at the gate. FFS!</strong> <span style="color:#555;">Very near Bus Station at 2:22pm</span>
</li>
<li><strong>Oh yeah! Arrived at #busstation #glasto #checkin /cc @glastonick @sdiddy</strong> <span style="color:#555;">At Bus Station at 2:25pm</span>
</li>
<li><strong>I can _see_ gate a. But I can also see a lot of people between me and gate a.</strong> <span style="color:#555;">Very near Bus Station at 3:02pm</span>
</li>
<li><strong>#checkin #glasto #gatea Finally!</strong> <span style="color:#555;">At Pedestrian Gate A at 3:30pm</span>
</li>
<li><strong>On way shopping passing brielfy #glade #checkin #glasto.</strong> <span style="color:#555;">At The Glade at 5:20pm</span>
</li>
<li><strong>Passing #tinyteatent on way for food. #checkin #glasto</strong> <span style="color:#555;">At The Tiny Tea Tent at 8:55pm</span>
</li>
<li><strong>Cider, but not at a bus. Rather Brothers cider. </strong> <span style="color:#555;">Very near Pie Minister at 9:10pm</span>
</li>
<li><strong>Brother&#8217;s. Oh yeah. </strong> <span style="color:#555;">Very near Pie Minister at 9:29pm</span>
</li>
<li><strong>This is all good. Fire time at glasto. And the Internet work. </strong> <span style="color:#555;">170m from HMS Sweet Charity at 10:56pm</span>
</li>
<li><strong>This is the camp site. </strong> <span style="color:#555;">170m from HMS Sweet Charity at 11:14pm</span>
</li>
</ul>
<h4>Thursday</h4>
<ul>
<li><strong>Where am I? Campsite. Late-o-clock with BHL</strong> <span style="color:#555;">Very near Le Grand Bouffe at 12:48am</span>
</li>
<li><strong>Breakfast with BHL and friends. Very much the raw prawn this morning. </strong> <span style="color:#555;">Very near Le Grand Bouffe at 11:08am</span>
</li>
<li><strong>Milling about. Wondering without aim!</strong> <span style="color:#555;">Very near Reggae Delights (TBC) at 12:23pm</span>
</li>
<li><strong>Sunbathing at #pyramid stage. #glasto #checkin</strong> <span style="color:#555;">At Pyramid at 1:40pm</span>
</li>
<li><strong>Still hanging out at #pyramid waiting for @sdiddy to get the hell out of his van! #checkin #glasto</strong> <span style="color:#555;">At Pyramid at 2:20pm</span>
</li>
<li><strong>Watching first live music at the bandstand! Yay!</strong> <span style="color:#555;">170m from HMS Sweet Charity at 4:10pm</span>
</li>
<li><strong>Having tea at the #tinyteatent &#8211; will be here for a bit. #glasto #checkin</strong> <span style="color:#555;">At The Tiny Tea Tent at 5:00pm</span>
</li>
<li><strong>Near the #glade watching the band who opened first #glasto at spirit of 71 stage. #checkin</strong> <span style="color:#555;">At The Glade at 6:05pm</span>
</li>
<li><strong>Still at #parkstage but heading off soon. #glasto #checkin</strong> <span style="color:#555;">At The Park Stage at 10:25pm</span>
</li>
</ul>
<h4>Friday</h4>
<ul>
<li><strong>Wakey wakey rise and shine! At #pyramid with @terrahawkes for first band of the day. #glasto #checkin</strong> <span style="color:#555;">At Pyramid at 11:00am</span>
</li>
<li><strong>At #westholts watching 30 drummers tearing it up. #glasto #checkin</strong> <span style="color:#555;">At West Holts at 12:30pm</span>
</li>
<li><strong>Passing #tinyteatent on way to Avalon. #glasto #checkin</strong> <span style="color:#555;">At The Tiny Tea Tent at 1:40pm</span>
</li>
<li><strong>Found real ale. At a bar. Neat Avalon I think. Hanging here. Is good. I have zero faith in GPS location ability!</strong> <span style="color:#555;">170m from HMS Sweet Charity at 2:09pm</span>
</li>
<li><strong>Listening to the mad hatters (i think) tear it up at #avalon. #glasto #checkin</strong> <span style="color:#555;">At Avalon at 2:45pm</span>
</li>
<li><strong>It&#8217;s official. @terrahawkes is a bad influence. At #avalon still. Good music here. #glasto #checkin</strong> <span style="color:#555;">At Avalon at 3:45pm</span>
</li>
<li><strong>Watching BB King at #pyramid #glasto #checkin</strong> <span style="color:#555;">At Pyramid at 4:55pm</span>
</li>
</ul>
<h4>Saturday</h4>
<ul>
<li><strong>Gentle introduction to the day at #tinyteatent. #glasto #checkin</strong> <span style="color:#555;">At The Tiny Tea Tent at 11:00am</span>
</li>
<li><strong>Managed to watch a band twice. #checkin #glade #glasto</strong> <span style="color:#555;">At The Glade at 12:35pm</span>
</li>
<li><strong>At #dance (west) for fujiya miyagi. #checkin #glasto</strong> <span style="color:#555;">At Dance Village at 1:05pm</span>
</li>
<li><strong>At #Avalon watching someone who is the champion of the world. #checkin #glasto</strong> <span style="color:#555;">At Avalon at 2:25pm</span>
</li>
<li><strong>In #avalon cafe with a coffee and the paper. Hedonistic! #glasto #checkin</strong> <span style="color:#555;">At Avalon at 2:40pm</span>
</li>
<li><strong>At #westholts with @sdiddy going to get a cider. The sun is out again! #glasto #checkin</strong> <span style="color:#555;">At West Holts at 3:15pm</span>
</li>
<li><strong>Still at #westholts. #checkin #glasto</strong> <span style="color:#555;">At West Holts at 4:20pm</span>
</li>
<li><strong>I appear to have not left #westholts yet. I blame @sdiddy. #checkin #glasto</strong> <span style="color:#555;">At West Holts at 5:15pm</span>
</li>
<li><strong>_still_ at #westholts. The sun is hot. I have a ukekele. All is good. /cc @Pikesley (start a band?) #glasto #checkin</strong> <span style="color:#555;">At West Holts at 5:30pm</span>
</li>
<li><strong>At #pyramid to see some band @sdiddy wants to see! #checkin #glasto</strong> <span style="color:#555;">At Pyramid at 6:05pm</span>
</li>
<li><strong>About to peak? #pyramid #glasto #checkin</strong> <span style="color:#555;">At Pyramid at 7:25pm</span>
</li>
<li><strong>Holy moly, it&#8217;s Elbow at #pyramid and I&#8217;ve just sung happy birthday! #checkin #glasto</strong> <span style="color:#555;">At Pyramid at 9:10pm</span>
</li>
<li><strong>Tell a lie. I mean #Avalon. #checkin #glasto</strong> <span style="color:#555;">At Avalon at 10:55pm</span>
</li>
</ul>
<h4>Sunday</h4>
<ul>
<li><strong>At #pyramid, so early the litter-pickers are still going and there&#8217;s no music. #checkin #glasto</strong> <span style="color:#555;">At Pyramid at 10:00am</span>
</li>
<li><strong>Watching fisherman&#8217;s friends. #checkin #glasto #pyramid</strong> <span style="color:#555;">At Pyramid at 11:05am</span>
</li>
<li><strong>Still at #pyramid. Staying for Paul Simon. #glasto #checkin /cc @sdiddy</strong> <span style="color:#555;">At Pyramid at 2:20pm</span>
</li>
<li><strong>Still at #pyramid. Paul Simon on next. #glasto #checkin</strong> <span style="color:#555;">At Pyramid at 3:55pm</span>
</li>
<li><strong>At #Avalon for Show of Hands. #glasto #checkin</strong> <span style="color:#555;">At Avalon at 6:05pm</span>
</li>
<li><strong>At #pyramid waiting for Beyoncé to start. #checkin #glasto</strong> <span style="color:#555;">At Pyramid at 9:55pm</span>
</li>
</ul>
<h4>Monday</h4>
<ul>
<li><strong>Heading out of #gatea. #checkin #glasto</strong> <span style="color:#555;">At Pedestrian Gate A at 7:40am</span>
</li>
<li> <span style="color:#555;">176km from the festival at 12:27pm</span>
</li>
</ul>
<h2>A final word</h2>
<p>It was great fun building a mobile app. I&#8217;m a firm believer that you should try to work on new things all the time to build your knowledge. A big thank you to my colleagues for the endless discussions and in particular <a href="http://twitter.com/oksannnna" target="_blank">@oksannnna</a> for the pin icons and <a href="http://twitter.com/paugay" target="_blank">@paugay</a> for all the frontend work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2011/07/25/glastofinder-writing-a-mobile-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocking Iterator with PHPUnit</title>
		<link>http://www.davegardner.me.uk/blog/2011/03/04/mocking-iterator-with-phpunit/</link>
		<comments>http://www.davegardner.me.uk/blog/2011/03/04/mocking-iterator-with-phpunit/#comments</comments>
		<pubDate>Fri, 04 Mar 2011 17:52:34 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[phpunit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=173</guid>
		<description><![CDATA[When writing unit tests, it is important that you isolate the system under test from any dependencies. Put simply, this means you have to mock any other objects that your system under test interacts with. This can be tricky when a dependency implements the Iterator interface as you have to carefully mock all calls to [...]]]></description>
			<content:encoded><![CDATA[<p>When writing <a href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit tests</a>, it is important that you isolate the system under test from any dependencies. Put simply, this means you have to mock any other objects that your system under test interacts with. This can be tricky when a dependency implements the <a href="http://php.net/manual/en/class.iterator.php" target="_blank">Iterator interface</a> as you have to carefully mock all calls to five methods in the correct order.</p>
<p>This blog post provides an example test showing how to mock an Iterator in PHPUnit as well as a helper class to make this process straightforward. You can <a target="_blank" href="http://pastebin.com/FVxNf6zq">view the source code for the helper on PasteBin</a> or <a href="/iterator.tar.gz">download the entire source code as a gzipped TAR</a>.</p>
<h3>Simple Iterator class</h3>
<p>To demonstrate, consider the following simple iterator class.</p>
<pre class="code">/**
 * Example list class
 *
 * @author Dave Gardner &lt;dave@davegardner.me.uk&gt;
 */
class exampleList implements Iterator
{
    /**
     * Our items
     *
     * @var array
     */
    private $items = array(
        'item1' =&gt; 'This is the first item',
        'item2' =&gt; 'This is the second item',
        'item3' =&gt; 'This is the third item',
        'item4' =&gt; 'This is the fourth item',
        'item5' =&gt; 'This is the fifth item'
    );

    /**
     * Get key of current item as string
     *
     * @return string
     */
    public function key()
    {
        echo "\033[36m" . __METHOD__ . "\033[0m\n";
        return key($this-&gt;items);
    }

    /**
     * Test if current item valid
     *
     * @return boolean
     */
    public function valid()
    {
        echo "\033[36m" . __METHOD__ . "\033[0m\n";
        return current($this-&gt;items) === FALSE
                ? FALSE
                : TRUE;
    }

    /**
     * Fetch current value
     *
     * @return string
     */
    public function current()
    {
        echo "\033[36m" . __METHOD__ . "\033[0m\n";
        return current($this-&gt;items);
    }

    /**
     * Go to next item
     */
    public function next()
    {
        echo "\033[36m" . __METHOD__ . "\033[0m\n";
        next($this-&gt;items);
    }

    /**
     * Rewind to start
     */
    public function rewind()
    {
        echo "\033[36m" . __METHOD__ . "\033[0m\n";
        reset($this-&gt;items);
    }
}</pre>
<p>Ignore the strange bash escape codes (I can't help myself when writing CLI scripts). Instantiated objects of this class will loop through their five internal items (when asked) and echo out the methods being called in cyan! We can see this in action via the following code:</p>
<pre class="code">echo "\n\033[44;37;01mTest 1: foreach key =&gt; value\033[0m\n\n";

$list = new exampleList();
foreach ($list as $key =&gt; $value)
{
    echo "\033[01m$key = $value\033[0m\n";
}

echo "\n\033[44;37;01mTest 2: foreach value\033[0m\n\n";

$list = new exampleList();
foreach ($list as $value)
{
    echo "\033[01m$value\033[0m\n";
}</pre>
<p>When we run this, we get the following.</p>
<p><a href="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/03/runningIterator.jpg"><img class="aligncenter size-full wp-image-175" title="Running the iterator" src="http://www.davegardner.me.uk/blog/wp-content/uploads/2011/03/runningIterator.jpg" alt="Running the iterator" width="422" height="792" /></a></p>
<h3>Mocking an Iterator for testing</h3>
<p>This shows us exactly which methods are called and in what order. We can now use this to write some tests for a <em>mocked</em> iterator. All we have to do with our mocked object is set up PHPUnit expectations; the key point being the use of the <a href="http://www.phpunit.de/manual/3.6/en/test-doubles.html#test-doubles.mock-objects.tables.matchers" target="_blank">at() matcher</a> to specify the exact sequence of calls. The following test applies this to allow us to iterate through three mocked items. You can <a target="_blank" href="http://pastebin.com/uCdwSK4i">view the full source on PasteBin</a>.</p>
<pre class="code">    public function testWhenMockThreeIterationWithNoKey()
    {
        $list = $this-&gt;buildSystemUnderTest();

        $list-&gt;expects($this-&gt;at(0))
             -&gt;method('rewind');

        // iteration 1
        $list-&gt;expects($this-&gt;at(1))
             -&gt;method('valid')
             -&gt;will($this-&gt;returnValue(TRUE));
        $list-&gt;expects($this-&gt;at(2))
             -&gt;method('current')
             -&gt;will($this-&gt;returnValue('This is the first item'));
        $list-&gt;expects($this-&gt;at(3))
             -&gt;method('next');

        // iteration 2
        $list-&gt;expects($this-&gt;at(4))
             -&gt;method('valid')
             -&gt;will($this-&gt;returnValue(TRUE));
        $list-&gt;expects($this-&gt;at(5))
             -&gt;method('current')
             -&gt;will($this-&gt;returnValue('This is the second item'));
        $list-&gt;expects($this-&gt;at(6))
             -&gt;method('next');

        // iteration 2
        $list-&gt;expects($this-&gt;at(7))
             -&gt;method('valid')
             -&gt;will($this-&gt;returnValue(TRUE));
        $list-&gt;expects($this-&gt;at(8))
             -&gt;method('current')
             -&gt;will($this-&gt;returnValue('And the final item'));
        $list-&gt;expects($this-&gt;at(9))
             -&gt;method('next');

        $list-&gt;expects($this-&gt;at(10))
             -&gt;method('valid')
             -&gt;will($this-&gt;returnValue(FALSE));

        $counter = 0;
        $values = array();
        foreach ($list as $value)
        {
            $values[] = $value;
            $counter++;
        }
        $this-&gt;assertEquals(3, $counter);

        $expectedValues = array(
            'This is the first item',
            'This is the second item',
            'And the final item'
        );
        $this-&gt;assertEquals($expectedValues, $values);
    }</pre>
<h3>Making this process simple via a helper</h3>
<p>There a bunch of other tests within the full source code; I&#8217;ve left them out here to spare you a huge code block! This is actually a win. We have mocked an iterator and it works as expected. The only downside is that there&#8217;s a lot of stuff to repeat each time. To avoid this we can simply make a helper method to do the job for us. You can <a target="_blank" href="http://pastebin.com/FVxNf6zq">view the source code for this on PasteBin</a>.</p>
<pre class="code">    /**
     * Mock iterator
     *
     * This attaches all the required expectations in the right order so that
     * our iterator will act like an iterator!
     *
     * @param Iterator $iterator The iterator object; this is what we attach
     *      all the expectations to
     * @param array An array of items that we will mock up, we will use the
     *      keys (if needed) and values of this array to return
     * @param boolean $includeCallsToKey Whether we want to mock up the calls
     *      to "key"; only needed if you are doing foreach ($foo as $k =&gt; $v)
     *      as opposed to foreach ($foo as $v)
     */
    private function mockIterator(
            Iterator $iterator,
            array $items,
            $includeCallsToKey = FALSE
            )
    {
        $iterator-&gt;expects($this-&gt;at(0))
                 -&gt;method('rewind');
        $counter = 1;
        foreach ($items as $k =&gt; $v)
        {
            $iterator-&gt;expects($this-&gt;at($counter++))
                     -&gt;method('valid')
                     -&gt;will($this-&gt;returnValue(TRUE));
            $iterator-&gt;expects($this-&gt;at($counter++))
                     -&gt;method('current')
                     -&gt;will($this-&gt;returnValue($v));
            if ($includeCallsToKey)
            {
                $iterator-&gt;expects($this-&gt;at($counter++))
                         -&gt;method('key')
                         -&gt;will($this-&gt;returnValue($k));
            }
            $iterator-&gt;expects($this-&gt;at($counter++))
                     -&gt;method('next');
        }
        $iterator-&gt;expects($this-&gt;at($counter))
                 -&gt;method('valid')
                 -&gt;will($this-&gt;returnValue(FALSE));
    }</pre>
<p>Now we can repeat our test using the more succinct:</p>
<pre class="code">    public function testWhenMockThreeIterationWithNoKey()
    {
        $list = $this-&gt;buildSystemUnderTest();

        $expectedValues = array(
            'This is the first item',
            'This is the second item',
            'And the final item'
        );
        $this-&gt;mockIterator($list, $expectedValues);

        $counter = 0;
        $values = array();
        foreach ($list as $value)
        {
            $values[] = $value;
            $counter++;
        }
        $this-&gt;assertEquals(3, $counter);

        $this-&gt;assertEquals($expectedValues, $values);
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2011/03/04/mocking-iterator-with-phpunit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Applying collective intelligence to PHP UK Conference 2011</title>
		<link>http://www.davegardner.me.uk/blog/2011/02/27/applying-collective-intelligence-to-php-uk-conference-2011/</link>
		<comments>http://www.davegardner.me.uk/blog/2011/02/27/applying-collective-intelligence-to-php-uk-conference-2011/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 20:34:56 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[collective intelligence]]></category>
		<category><![CDATA[jaccard]]></category>
		<category><![CDATA[joind.in]]></category>
		<category><![CDATA[pearson correlation]]></category>
		<category><![CDATA[phpuk2011]]></category>
		<category><![CDATA[recommendation]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=163</guid>
		<description><![CDATA[This post covers the use of basic collective intelligence techniques to analyse talk ratings on joind.in from the PHP UK Conference 2011. It explains how to use a similarity algorithm to power a "users like me like" recommendation system.]]></description>
			<content:encoded><![CDATA[<p>I had a cracking time at the <a target="_blank" href="http://www.phpconference.co.uk/">PHP UK Conference</a> this year. It&#8217;s usually pretty good, but this year I thought the talks were slightly better than normal. I think the free beer at the end always helps!</p>
<p>This got me wondering.</p>
<blockquote><p>What talks did I miss out on that I would have liked?&rdquo;</p></blockquote>
<p>As you may be aware, many delegates have been using <a target="_blank" href="http://joind.in/event/view/506">joind.in</a> to provide feedback on the talks. It turns out that <a target="_blank" href="http://joind.in/api">joind.in have an API</a>, and this, in turn, means we can carry out some basic <a target="_blank" href="http://en.wikipedia.org/wiki/Collective_intelligence">collective intelligence</a> techniques to provide &ldquo;recommendations&rdquo; on what other talks would have been of interest.</p>
<p>The term &ldquo;<a target="_blank" href="http://en.wikipedia.org/wiki/Collective_intelligence">collective intelligence</a>&rdquo; refers to intelligence that emerges from the collaboration of a group. In this case, we can leverage the data within joind.in and make &ldquo;intelligent&rdquo; recommendations.</p>
<p>This post looks at building a simple recommendation engine using the data from joind.in. You can <a href="/phpuk2011.php.gz">download the entire source code here (gzipped)</a> or <a target="_blank" href="http://pastebin.com/6pyFrNyA">view via PasteBin here</a> and try it out for yourself.</p>
<h3>The joind.in API</h3>
<p>The API is not entirely simple to understand, and examples are fairly thin on the ground within the documentation. The main thing to figure out is that you have to POST data to the appropriate API end point, where the POST data itself contains the &ldquo;action&rdquo; to carry out.</p>
<p>This PHP function uses CURL to fetch API data via JSON, constructing the correct data to POST.</p>
<pre class="code">
/**
 * Hit the Joind.in API
 *
 * @param string $endPoint API end point, eg: "event" to hit event API
 * @param string $action The desired action, eg: "gettalks"
 * @param array $params Any params to send
 *
 * @return array Decoded JSON data
 */
function joindInApi($endPoint, $action, array $params = array())
{
    $requestData = array(
        'request' => array(
            'action' => array(
                'type' => $action,
                'data' => $params
            )
        )
    );
    $options = array(
        CURLOPT_RETURNTRANSFER => TRUE,     // return web page
        CURLOPT_HEADER         => FALSE,    // don't return headers
        CURLOPT_FOLLOWLOCATION => TRUE,     // follow redirects
        CURLOPT_ENCODING       => '',       // handle all encodings
        CURLOPT_USERAGENT      => 'DAVE!',  // who am i
        CURLOPT_AUTOREFERER    => TRUE,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_HTTPHEADER     => array('Content-Type: application/json'),
        CURLOPT_POSTFIELDS     => json_encode($requestData)
    );

    $ch = curl_init('http://joind.in/api/' . $endPoint);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    return json_decode($content, TRUE);
}
</pre>
<h3>Grab talks and ratings</h3>
<p>The first thing we need to do is fetch all the talks for the conference along with any user ratings. We can do this via the <a target="_blank" href="http://joind.in/api#get_evt_talks">Event API &ldquo;gettalks&rdquo; action</a> followed by the <a target="_blank" href="http://joind.in/api#get_talk_comments">Talk API &ldquo;getcomments&rdquo; action.</a></p>
<pre class="code">
// Phase 1: grab ratings via the Join.in API

$userRatings = array();     // [userId][talkId] = rating
$talkTitles = array();      // we'll store these for later

$talks = joindInApi('event', 'gettalks', array('event_id' => 506));
foreach ($talks as $talk)
{
    $talkTitles[$talk['ID']] = $talk['talk_title'];
    echo $talk['ID'] . "\t" . $talk['talk_title'] . "\n";
    $comments = joindInApi('talk', 'getcomments', array('talk_id' => $talk['ID']));
    foreach ($comments as $comment)
    {
        echo ' -> ' . $comment['uname'] . "\t" . $comment['rating'] . "\n";
        $userRatings[$comment['uname']][$talk['ID']] = $comment['rating'];
    }
}
</pre>
<h3>Calculating similar users</h3>
<p>To work out recommendations we&#8217;ll use the classic &ldquo;people like me like&rdquo; method (a type of <a target="_blank" href="http://en.wikipedia.org/wiki/Collaborative_filtering">collaborative filter</a>). This works by calculating a similarity score between a user and every other user. This is easy to implement and works well for small users sets. Companies with a <em>lot</em> of users, for example Amazon, usually use item-based collaborative filtering instead of user-based, due to the difficulty in calculating similarity between every user at this scale.</p>
<p>There are many different algorithms that will score how similar two users are, based on a set of data. Examples include <a target="_blank" href="http://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distance</a>, <a target="_blank" href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard index</a> and <a target="_blank" href="http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient">Pearson correlation</a>.</p>
<p>It is often very difficult to know which distance algorithm will give best results and therefore the best advice is to try them all out! We will use the Pearson correlation in this example.</p>
<p>The following is a PHP implementation of Pearson, borrowing heavily from the excellent beginners book <a target="_blank" href="http://oreilly.com/catalog/9780596529321">Programming Collective Intelligence</a>.</p>
<pre class="code">
/**
 * Calculate pearson distance
 *
 * This calculates the pearson correlation between user1 and user2; a measure
 * of how similar users are.
 *
 * @param array $userRatings Our array of user ratings; [userId][talkId] = rating
 * @param string $user1 The first userId
 * @param string $user2 The second userId
 *
 * @return integer|float A number between -1 and 1, where -1 indicates very
 *      dissimilar, and 1 indicates very similar
 */
function calculatePearson($userRatings, $user1, $user2)
{
    // get list of talks both have rated
    $talks = array_keys(array_intersect_key(
            $userRatings[$user1],
            $userRatings[$user2]
            ));
    $numBothHaveRated = count($talks);
    if ($numBothHaveRated === 0)
    {
        $pearson = 0;
    }
    else
    {
        $sumOfRatingsUser1 = 0;
        $sumOfSquareOfRatingsUser1 = 0;
        $sumOfRatingsUser2 = 0;
        $sumOfSquareOfRatingsUser2 = 0;
        $sumOfProducts = 0;

        foreach ($talks as $talkId)
        {
            $sumOfRatingsUser1 += $userRatings[$user1][$talkId];
            $sumOfSquareOfRatingsUser1 += pow($userRatings[$user1][$talkId], 2);
            $sumOfRatingsUser2 += $userRatings[$user2][$talkId];
            $sumOfSquareOfRatingsUser2 += pow($userRatings[$user2][$talkId], 2);
            $sumOfProducts += $userRatings[$user1][$talkId] * $userRatings[$user2][$talkId];
        }

        // calculate pearson
        $numerator = $sumOfProducts - ($sumOfRatingsUser1 * $sumOfRatingsUser2 / $numBothHaveRated);
        $denominator = sqrt(
                ($sumOfSquareOfRatingsUser1 - pow($sumOfRatingsUser1, 2) / $numBothHaveRated)
              * ($sumOfSquareOfRatingsUser2 - pow($sumOfRatingsUser2, 2) / $numBothHaveRated)
                );
        if ($denominator == 0)
        {
            $pearson = 0;
        }
        else
        {
            $pearson = $numerator / $denominator;
        }
    }

    return $pearson;
}
</pre>
<p>We can now run through all the users we found (who had provided comments!) and work out their similarity with every other user.</p>
<pre class="code">
// Phase 2: Calculate user similarity (via Pearson correlation)

$pearson = array();

$users = array_keys($userRatings);
foreach ($users as $user1)
{
    foreach ($users as $user2)
    {
        if ($user1 !== $user2 &#038;&#038; !isset($pearson[$user1][$user2]))
        {
            $value = calculatePearson(
                    $userRatings,
                    $user1,
                    $user2
                    );
            $pearson[$user1][$user2] = $value;
            $pearson[$user2][$user1] = $value;
            echo $user1 . "\t" . $user2 . "\t" . $value . "\n";
        }
    }
}

echo "\nLike me:\n";

arsort($pearson[WHO_AM_I]);
foreach ($pearson[WHO_AM_I] as $user => $value)
{
    echo $user . "\t" . $value . "\n";
}
</pre>
<p>So who is like me? Turns out it&#8217;s these guys:</p>
<ul>
<li>welworthy = 1</li>
<li>ianb = 1</li>
<li>manarth = 1</li>
<li>m.whitby@gmail.com = 0.99999999999999</li>
<li>rowan_m = 0.5</li>
</ul>
<h3>Providing recommendations</h3>
<p>Now I know the users who are most similar to me, I can see which talks they liked. The following recommendation algorithm does just this, weighting all talks according to how similar I am to them.</p>
<pre class="code">
/**
 * Get recommendations
 *
 * Return recommendations on talks I _should_ have seen (if I could have!)
 *
 * @param array $userRatings Our user ratings; [userId][talkId] = rating
 * @param string $user The user to get recommendations for
 * @param array $similarities The similarities of all users; [user1][user2] = #
 *
 * @return array [talkId] = &lt;how much you should have seen it!&gt;
 */
function getRecommendations(array $userRatings, $user, array $similarities)
{
    $totals = array();
    $similaritySums = array();

    foreach ($userRatings as $compareWithUser => $talksWithRatings)
    {
        // don't compare against self
        if ($user === $compareWithUser)
        {
            continue;
        }

        // how similar?
        $similarity = $similarities[$user][$compareWithUser];
        // ignore users if they aren't similar (&lt;=0)
        if ($similarity &lt;= 0)
        {
            continue;
        }

        foreach ($talksWithRatings as $talkId =&gt; $rating)
        {
            // skip if I saw this talk
            if (isset($userRatings[$user][$talkId]))
            {
                continue;
            }
            if (!isset($totals[$talkId]))
            {
                $totals[$talkId] = 0;
            }
            $totals[$talkId] += $rating * $similarity;
            if (!isset($similaritySums[$talkId]))
            {
                $similaritySums[$talkId] = 0;
            }
            $similaritySums[$talkId] += $similarity;
        } // end foreach talks
    } // end foreach users

    // generate normalised list
    foreach ($totals as $talkId =&gt; &#038;$score)
    {
        $score /= $similaritySums[$talkId];
    }

    arsort($totals);

    return $totals;
}
</pre>
<p>The final stage is to run this through for me!</p>
<pre class="code">
// Phase 3: Get recommendations

echo "\nRecommended talks:\n";

$recommendations = getRecommendations($userRatings, WHO_AM_I, $pearson);
foreach ($recommendations as $talkId =&gt; $recommendation)
{
    echo $talkId . "\t" . $talkTitles[$talkId] . " ($recommendation)\n";
}
</pre>
<p>So my final recommendations are (with a rating in brackets):</p>
<ul>
<li>2514: Beyond Frameworks (5)</li>
<li>2511: 99 Problems, But The Search Ain&#8217;t One (5)</li>
<li>2512: Advanced OO Patterns (5)</li>
<li>2521: Varnish in Action (4)</li>
<li>2520: Running on Amazon EC2 (4)</li>
<li>2513: Agility and Quality (3)</li>
</ul>
<h3>Conclusion</h3>
<p>When I first ran this through on Saturday evening, my recommendations did not include &ldquo;Beyond Frameworks&rdquo; nor &ldquo;Agility and Quality&rdquo;. Now, on Sunday evening, there is more data and these have popped up. I think I prefer my Saturday evening list, but it&#8217;s not too far off.</p>
<p>It would be interesting to experiment with different similarity algorithms to see what impact this has. It would also be cool to use the joind.in API to look at <em>other</em> talks that my similar users have rated positively, outside of this conference. These are left as exercises for the reader!</p>
<p>If you&#8217;re interested in learning more I&#8217;d recommend starting with the O&#8217; Reilly book, <a target="_blank" href="http://oreilly.com/catalog/9780596529321">Programming Collective Intelligence</a>. The examples take a bit of work to fully understand, but it shields you from the Maths.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2011/02/27/applying-collective-intelligence-to-php-uk-conference-2011/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why you should always use PHP interfaces</title>
		<link>http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/</link>
		<comments>http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 16:06:17 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[crc]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[interfaces]]></category>
		<category><![CDATA[lazy load]]></category>
		<category><![CDATA[virtual proxy]]></category>

		<guid isPermaLink="false">http://www.davegardner.me.uk/blog/?p=142</guid>
		<description><![CDATA[This post was sparked by a very simple question from an ex-colleague "Why bother with PHP interfaces?" It gives two reasons - firstly as a way of making you think in the right way when conducting Object Oriented design; secondly because interfaces are essential for flexible code, as demonstrated via the Virtual Proxy pattern.]]></description>
			<content:encoded><![CDATA[<p>This post was sparked by a very simple question from an ex-colleague:</p>
<blockquote><p>Why bother with PHP interfaces?</p></blockquote>
<p>The subtext here was that the classes themselves contain the interface definition (through the methods they define) and hence interfaces are not needed, particularly where there is only one class that implements a given interface. One response to this question would be &ldquo;hang on, <a href="http://lmgtfy.com/?q=why+use+php+interfaces">let me Google that for you</a>&rdquo;. However the question got me thinking about how best to demonstrate the purpose and power of interfaces. Plus there isn&#8217;t that much good stuff out there about the use of PHP interfaces.</p>
<h3>Why interfaces?</h3>
<h4>1. It helps you think about things in the right way</h4>
<p>Object oriented design is hard. It&#8217;s usually harder for programmers, like myself, who started out in a procedural world. Allen Holub sums it up nicely in the primer section of his book <a href="http://www.davegardner.me.uk/reading/holub-on-patterns/">Holub on Patterns</a> (which includes much of <a href="http://www.javaworld.com/javaworld/jw-07-1999/jw-07-toolbox.html?page=2">this article from Javaworld</a>) when he explains how people often think that an &#8220;object is a datastructure of some sort combined with a set of functions&#8221;. As Holub points out &#8211; this is incorrect.</p>
<blockquote><p>First and foremost, an object is a collection of <em>capabilities</em>. An object is defined by what it can do, not by how it does it &#8212; and the data is part of &#8220;how it does it.&#8221; In practical terms, this means that an object is defined by the messages it can receive and send; the methods that handle these messages comprise the object&#8217;s sole interface to the outer world.</p></blockquote>
<p>It&#8217;s a subtle distinction, especially for those of us with a procedural background. Thinking in terms of these messages is hard; in the same way that <a href="http://php.net/manual/en/language.oop5.static.php">static methods in PHP</a> and <a href="http://en.wikipedia.org/wiki/God_object">&#8220;God&#8221; objects</a> seem so much more familiar. Making wide use of interfaces when building an application is an easy way of getting out of these bad habits.</p>
<p>When I&#8217;m trying to design an OO system I usually start with <a href="http://en.wikipedia.org/wiki/Class-responsibility-collaboration_card">Cunningham and Beck&#8217;s CRC cards (Class, Responsibility, Collaboration)</a>. This approach involves writing down on a separate index card (or small piece of paper) the name of each class, what its responsibility is and which other classes it collaborates with. From here, I then define the public interface of each class (the methods that handle the messages it can send and receive).</p>
<p>Thinking in the right way is the biggest advantage of interfaces, because it is the hardest thing to get right.</p>
<h4>2. It makes for more future-proof code</h4>
<p>Having a separate interface for every domain object may at first seem like overkill. Why bother? One reason is the flexibility it gives you going forward. An example of this is the <a href="http://martinfowler.com/eaaCatalog/lazyLoad.html">Virtual Proxy lazy-load pattern</a>. This relies on a placeholder object having exactly the same <strong>interface</strong> as a real domain object. Whenever one of the Virtual Proxy&#8217;s methods is called, it will lazy-load the actual object itself and then pass the message through. Stefan Preibsh recently gave a talk that includes this pattern entitled <a href="http://www.slideshare.net/spriebsch/a-new-approach-to-object-persistence">&#8220;A new approach to object persistence&#8221;</a> which is well worth a read.</p>
<p>The interesting thing here is that by making classes that collaborate with a given class rely only on interface rather than concrete class we can implement a Virtual Proxy pattern <em>at any time</em>, safe in the knowledge none of our application will break!</p>
<pre class="code">// this is good - userInterface is an interface name
public function sendReminder(userInterface $user)
{
    // do something
}
// this is less good! user is a specific class implementation
public function sendReminder(user $user)
{
    // do something
}</pre>
<p>The following simple example shows the Virtual Proxy pattern in action.</p>
<pre class="code">// our interface
interface userInterface
{
    public function isMember();
}

// our concrete user class
class user implements userInterface
{
    private $paidUntil;

    public function __construct($paidUntil)
    {
        $this-&gt;paidUntil = $paidUntil;
    }
    public function isMember()
    {
        return $paidUntil &gt; time();
    }
}

// our proxy
class userProxy implements userInterface
{
    private $dao;
    private $user;
    private $userId;

    public function __construct($dao, $userId)
    {
        $this-&gt;dao = $dao;
        // set user to NULL to indicate we haven't loaded yet
        $this-&gt;user = NULL;
    }

    public function isMember()
    {
        if ($this-&gt;user === NULL)
        {
            $this-&gt;lazyLoad();
        }
        return $this-&gt;user-&gt;isMember();
    }

    private function lazyLoad()
    {
        $this-&gt;user = $this-&gt;dao-&gt;getById($this-&gt;userId);
    }
}</pre>
<p>Now let&#8217;s assume we have some other part of our code that collaborates with the user object to find out if someone is a member.</p>
<pre class="code">class inviteList
{
    public function add(userInterface $user)
    {
        if (!$user-&gt;isMember())
        {
            throw new youMustPayException('You must be a member to get an invite.');
        }
        // do something else
    }
}</pre>
<p>Our <em>inviteList</em> class does not care what type of object it receives (proxy or real), it simply requires something that implements <em>userInterface</em>.</p>
<p>The same argument holds true for the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator pattern</a>; by programming to interface each collaborator doesn&#8217;t care which concrete implementation (the outer-most decorated layer) it is given, as long as it adheres to the right interface.</p>
<p>In a nut shell: <strong>always programme to interface</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<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[Cassandra]]></category>
		<category><![CDATA[PHP]]></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>4</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>32</slash:comments>
		</item>
	</channel>
</rss>

