Archive for November, 2009

posted on Monday 23rd November 2009 by Dave

PHP dependency strategies: dependency injection and service locator

In this post I’m hoping to answer my own question: what strategy shall I use for handling dependencies in my new project? I’m going to explore three possible strategies that should help create good quality, uncoupled code:

  1. Simple Dependency Injection (DI)
  2. The Service Locator pattern
  3. A DI framework

This includes a bespoke implementation of a DI framework for PHP that automatically creates configuration by conducting a simplistic static analysis of code.

What are dependencies

Consider the following code. This simple application comprises a simple event domain object combined with a Data Access Object (DAO) that deals with persistance.

event.class.php
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";
    }
}
eventDao.class.php
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);
    }
}

An event object is dependant on a money object and a date object. It needs to create these to function correctly.

An eventDao object is dependant on a database object and an event object. It needs the database object to get the data and it needs to create and return a new event object.

Why are depedencies problematic?

Dependencies are not in themselves problematic. It is going to be impossible to write any useful code that doesn’t have some dependencies. The problem is how we handle those the dependencies. The code example provided above presents the following problems.

1. It makes testing impossible

Writing a unit test for the event object will inevitably end up testing the money and date 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 integration test rather than a unit test. Instead of testing the logic of the specific, isolated “unit” (our event object), we are instead testing the event object works in relation to the rest of the program.

While it may not seem immediately obvious why that’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 getById method without inadvertantly testing the database object. Without a fully-functioning database, setup with the expected data, our unit test will fail. Again, this isn’t a unit test, it’s more likely an intergration test or possibly even a system test.

2. The objects are tightly coupled

The eventDao class is tightly coupled to the specific concrete classes event and database. What if we want to use a different database object on our test environment? We can’t. Of course there’s ways round this immediate problem without changing too much at all. We could use global constants DATABASE_NAME, DATABASE_USER etc.. Don’t even go there! Tight coupling makes for brittle code. If you’re not convinced you can read this article or spend 10 minutes with Google.

3. It goes against the Don’t Repeat Yourself (DRY) principle

If we imagine adding some other domain objects and DAOs to our system we will end up repeating the new database() line again and again. The same goes for other domain objects that want to represent information internally as a date object.

An alternative coupling

Let’s say you’ve got this in your DAO instead:

        $db = database::getInstance();

Same problems! We probably still can’t test it (unless we have some kind of database::setInstance() method) and it’s certainly still tightly coupled regardless.

Strategy 1: Dependency Injection

Dependency Injection is very straightforward. In fact it’s so straightforward you’ve almost certainly already done it, even if you didn’t refer to it as DI. Fabien Potencier of Symfony fame explains it expertly in these slides.

To make use of dependency injection, our eventDao can be updated to:

eventDao.class.php
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);
    }
}
$db = new database('localhost','mydb','user','password');
$dao = new eventDao($db);
$event = $dao->getById(1);

We can now test the getById method using a mock database object because we are injecting the dependency into the DAO object.

We can’t, however, isolate testing of the DAO completely because of the event dependency. This can be fixed by delegating responsibility for event creation to a Factory.

eventFactory.class.php
class eventFactory
{
    public function create($row)
    {
        return new event($row);
    }
}
eventDao.class.php
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);
    }
}

Our code is now loosely coupled and we are programming to interface (allbeit that I haven’t actually put any interfaces into the code at this stage!) To quote kdgregory from StackOverflow:

Programming to an interface is saying “I need this functionality and I don’t care where it comes from.”

By putting in place a factory for creating objects we can program only to the interface we require. In our event class, this means we don’t have to rely on specific concrete implementations for date and money, instead we merely require some object that implements iDate and iMoney, and we can use a factory to make us one of those objects.

Inversion of Control (IoC)

It’s worth noting that by injecting dependencies into the objects we have inverted 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 ‘call back’ on it. The term “Inversion of Control” seems to come up frequently when reading about DI, although I’m not sure that it’s always that clearly explained. Fowler explains it in this article. There are also some other interesting blog posts on the subject. If you want the short answer on what IoC is, check out this definition.

Object graphs

Using DI, what we inevitably end up with is a complex object graph. An object graph is simply a set of interconnected objects. In the case of DI, we have lots of interconnected objects since we are passing all our dependencies around as objects – so we end up with a lot of objects related to a lot of other objects at run time!

Strengths

This form of dependency injection is easy to understand. We avoid tight coupling, we can test our code and we are programming to interface. All is good!

Weaknesses

One of the web apps I work on uses a Front Controller pattern to handle incoming requests. The bootstrap code looks a bit like this:

$fc = new frontController();
$fc->dispatch();

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 all dependencies needed by the entire application into the constructor of the front controller! This post by Ben Scheirman on StackOverflow gives another example:

var svc = new ShippingService(new ProductLocator(),
   new PricingService(), new InventoryService(),
   new TrackingRepository(new ConfigProvider()),
   new Logger(new EmailLogger(new ConfigProvider())));

You get the idea.

We could be pragmatic about this and suggest that individual page controllers are allowed to be tightly coupled to domain objects. However it merely defers the inevitable.

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 use that object. This becomes a recursive task so the change causes a ripple effect to other code. The documentation to Google Guice explains it quite well (scroll down to the “Dependency Injection” section – due to their clever reader thing I can’t get an anchor link straight to it!) This problem relates to the inherent complexity involved in creating a large object graph.

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’s useful to have a framework. Otherwise you’ll need to construct dependencies recursively when you need to use a service

Strategy 2: Service Locator

Martin Fowler explains the idea of a service locator in detail in his article on the subject of DI. I’m going to explain it in the context of a PHP application.

A service locator is a straight forward system whereby objects can “look up” any dependencies they need from a central source. This gives the following advantages:

  • It is easy to add a dependency to any object
  • It is easy to replace which dependency is provided project wide, so we are adhering to the DRY principle
  • It removes tight coupling between objects

The simplest service locator may look like:

serviceLocator.class.php
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();
    }
}

Our DAO now becomes:

eventDao.class.php
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);
    }
}

For testing we’d need to add in equivalent methods like serviceLocator::setMoneyFactory and serviceLocator::setDatabase.

We can simplify (or complicate depending on your point of view) our service locator by replacing methods like serviceLocator::getMoneyFactory() with a more generic serviceLocator::getService($serviceName). We could then configure the service locator in our bootstrap with calls to serviceLocator::registerService($serviceName, $object). 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.

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 single object – 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:

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.

In terms of practical implementations, Mutant PHP has published an article on this subject which includes a sample service locator class.

The fairly new Symfony Dependency Injection Container appears to be based around the idea of a service locator. I say this because it doesn’t implement an inversion of control mechanism – as covered in strategy 3.

Strengths

The service locator provides a simple strategy for managing dependencies that is easily understood. It allows for testing and it avoids tight coupling between classes.

Weaknesses

The use of a service locator leads to a tight coupling between classes and the service locator itself.

Strategy 3: DI Framework

A dependency injection “framework” is an alternative strategy for dealing with dependencies to the arguably simpler service locator. They key idea is to stick with depedency injection (either into the constructor or via a setter), but have some external object (Fowler calls this an “assembler” in his article on the subject) actually deal with managing the dependencies, injecting them into objects as required, without the user having to worry about it.

Now coming from a PHP background, I’ve searched about for PHP-specific information on DI frameworks. So far, I haven’t managed to find anything that I feel explains the concept as well as the Guice documention does. In terms of responsiblity-driven design, Guice outlines the role of the “injector“ (Fowler’s “assembler”):

The injector’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.

This sounds promising, although I’m not 100% convinced I need a DI framework, I’m starting to see some advantages. There is an interesting discussion on StackOverflow (again!) about the need for a DI framework.

A bespoke DI Framework

To help understand the advantages of a DI framework I built my own, which I’ve rather confusingly called a “Service Injector”. As Benjamin Eberlei explains in a blog post on the subject of DI:

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

Having recently read the excellent Coders at Work (go and buy it now if you haven’t read it), I took some advice from Donald Knuth who said:

The problem is that coding isn’t fun if all you can do is call things out of a library, if you can’t write the library yourself.

So I decided to write my own.

Design motivations

In Benjamin’s post, he goes on to say:

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.

I think my motivations for DI framework are somewhat different. I don’t see myself wanting to “re-wire” an application at a later date.
Ideally I want my logic and wiring to remain clear at the code level; I personally don’t want to delegate all the wiring to some configurator – 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 dependencies automatically.

This led me to make the following decisions:

  • I wanted an automated builder; something that would look at the code and get the DI framework setup ready to go – based on class names and interfaces
  • I wanted to keep Factory classes; I think it makes logical sense to have a class who’s responsibility is to create new objects of type blah

A sample application

At the top level, I can ask the DI framework to create me an object:

// 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);

The DAO object is created, along with its dependencies; this all happens simply by annotating the code within the PHPDocumentor style comment blocks:

    /**
     * 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
     * @inject This informs the DI builder to inject constructor parameters on object creation
     */
    public function __construct(iDatabase $database, iEventFactory $eventFactory)

The service injector will find a class that implements iDatabase and iEventFactory and automatically inject these on object creation. The interesting thing is that either of these two services can have their own dependencies. For example, my eventFactory class declaration looks like this:

class eventFactory extends factory implements iEventFactory

It extends the Layer Supertype factory. The factory base class has a method to set its own dependency, again specified via annotation:

    /**
     * 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;
    }

The service injector will happily go away and recursively assemble the required objects and their dependencies.

The builder

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

Right now, it works as well as it needs to for the sample application. However it doesn’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 blah interface – in this situation it will fail. You’ll notice that although I’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 to interface and thinking about messages that the objects send other objects.

Pros and cons

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 interface: a service is simply some object that will provide a set of capabilities and the service injector’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’s OK since a string is not a service – and I set out to build something that would only do that job.

I guess that’s where my service injector differs from other implementations of dependency injection containers – 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!

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 – simply by changing one line of code.

The source code

So I’ve written this tool purely as a way to learn about the ideas involved and also to see if I could find a structure that I thought was useful for my application. It’s been done pretty quickly but if you’d like to have a closer look you can browse the source code here.

Other implementations for PHP

Conclusions

Through this process of research I have come to the following conclusions:

  • I prefer DI over a service locator because the individual modules are cleaner; dependencies are passed in rather than the object itself going and asking for them
  • A DI framework seems the way to go, simply to reduce the complexity involved in manually creating complex object graphs
  • I like Factory classes because they serve a clear purpose and make code easy to understand
  • I want a DI framework to be able to work (almost) completely from the source code

My next step is to look more closely at existing implementations to see if they could work in a production project.

posted on Monday 9th November 2009 by Dave

Setting up continuous integration for PHP using Hudson and Phing

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

One of the best explanations of Unit Testing I’ve read was posted by benzado on Stack Overflow.

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’s an initial rush, which is great, but after a few days you start to wonder if it is worth the trouble.

The difficulty with Unit Testing is keeping it up. It is very easy to slip into poor habits and before you know it there’s a huge chunk of code with no tests. Possibly a huge, badly designed chunk of code, that didn’t benefit from having tests written before it was coded. Before you know what’s going on, you end up with a project that you really can’t write tests for, because retrofitting the tests is near impossible.

For me, there are two critical reasons for Unit Testing:

  1. Enforcing good design
    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.
  2. Allowing changes to be made in confidence
    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 pretty convinced you haven’t messed up something else.

Continuous integration

Martin Fowler describes the process of Continuation Integration in detail. He suggests:

Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily – 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.

The key idea behind CI is to do what is most painful often, namely “building” everyone’s code from source and making sure it all works.

A CI system usually consists of the following key elements:

Continuous integration

Continuous integration

  • Developers commit code
  • CI server detects changes
  • CI server checksout code, runs tests, analyses code
  • CI server feeds back to development team

If you want to find out more about CI, I recommend the excellent book Continuous Integration: Improving Software Quality and Reducing Risk. There is an excerpt published on JavaWorld which covers a lot of the key advantages. In particular, it highlights:

1. Reduce risks
2. Reduce repetitive manual processes
3. Generate deployable software at any time and at any place
4. Enable better project visibility
5. Establish greater confidence in the software product from the development team

CI gets the most out of Unit Tests by forcing them to be run after every change. Not only that, but with a good CI setup, developers instantly know if they haven’t written enough tests. If avoids the situtation where Joe Bloggs has added in a huge chunk of code with zero tests.

Setting up CI for a PHP project

To get my environment setup, I consulted the following blog posts which are worth a read:

  1. http://blog.jepamedia.org/2009/10/28/continuous-integration-for-php-with-hudson/
  2. http://toptopic.wordpress.com/2009/02/26/php-and-hudson/

I’m assuming you’re using a CentOS 5 server (or I guess RHEL5). If not, you may still find various parts of this useful.

1. Install JDK

EPEL provide a set of CentOS packages, including a package for openJDK. This is the easiest way of installing Java.

Firstly, setup EPEL:

wget -O /etc/yum.repos.d/hudson.repo http://hudson-ci.org/redhat/hudson.repo

Next install OpenJDK:

yum install java-1.6.0-openjdk

2. Install Hudson

Download and install the CentOS RPM for Hudson:

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

Now Hudson is installed, we can start using the standard CentOS “service” command.

service hudson start

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’t do an exhaustive analysis before I decided on Hudson, it just seemed right to me.

To get the graphing engine working for Hudson, you may need to install x.

yum groupinstall base-x

3. Install phing

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

Make sure PEAR is installed for PHP (this is the easiest way of installing phing):

yum install php-pear

Then install the PEAR phing package:

pear channel-discover pear.phing.info
pear install phing/phing

4. Setup SVN

If you haven’t got a Subversion repository, you’re going to need one (or some other SCM tool like CVS, GIT or Mercurial).

yum install mod_dav_svn

The simplest setup involves creating a repo in /var/www/svn/<my repo>

mkdir -v /var/www/svn/test
svnadmin create --fs-type fsfs /var/www/svn/test
chown –R apache:apache /var/www/svn/test

Setup Apache by pretty much uncommenting the lines in /etc/httpd/conf.d/subversion.conf. Once Apache restarted, you’ll be able to get to it via /repos/test, assuming you’re using the default settings (sets up SVN on /repos). I haven’t gone into the details of getting SVN up and running; there are lots of resources out there that will help you do this.

5. Install PHP tools

PHPDocumentor – to generate documentation automatically from code
pear install PhpDocumentor
PHP CPD – “copy and paste detector” for PHP

This requires PHP 5.2. At time of writing, this wasn’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:

[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

Then you can do:

yum update php

You may also need to upgrade pear; if the install of phpcpd fails (below). To do this, try:

pear upgrade pear

or, if this wants to be forced, and you think it’s a good idea (I did):

pear upgrade --force pear

Finally we can install phpcpd!

pear channel-discover pear.phpunit.de
pear install phpunit/phpcpd
PHP Depend – help analyse quality of codebase

Note you may have update PHP to include the DOM module (first line below).

yum install php-dom
pear channel-discover pear.pdepend.org
pear install pdepend/PHP_Depend-beta
PHP Code Sniffer – analyse code for adherence to style/standards
pear install PHP_CodeSniffer-1.2.0
PHP Unit – unit test framework for PHP
pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit

To make PHP Unit work, we need XDebug installed, the PHP profiler.

yum install php-devel gcc
pecl install xdebug

6. Install Hudson plugins

Use the web interface to install the following plugins (Manage Hudson -> Plugins).

  • Checkstyle
  • Clover
  • DRY
  • Green Balls (handy because it shows successful builds as green circles rather than blue)
  • JDepend
  • xUnit (will handle the output of PHPUnit test results XML)

7. Setup the phing build script

The Phing build script defines what steps will be taken to “build” the application.

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.

/var/lib/hudson/jobs/Test/workspace/

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’ll keep this within the workspace) plus we run tests etc…

We’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

<?xml version="1.0" encoding="UTF-8"?>
 <project name="test" basedir="." default="app">
    <property name="builddir" value="${ws}/build" />

    <target name="clean">
        <echo msg="Clean..." />
        <delete dir="${builddir}" />
    </target>

    <target name="prepare">
        <echo msg="Prepare..." />
        <mkdir dir="${builddir}" />
        <mkdir dir="${builddir}/logs" />
        <mkdir dir="${builddir}/logs/coverage" />
        <mkdir dir="${builddir}/docs" />
        <mkdir dir="${builddir}/app" />
    </target>

    <!-- Deploy app -->
    <target name="app">
        <echo msg="We do nothing yet!" />
    </target>

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

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

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

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

    <!-- Unit Tests & coverage analysis -->
    <target name="phpunit">
        <echo msg="PHP Unit..." />
        <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"/>
    </target>
</project>

8. Setup Hudson

The first step is to create a new job.

  • From the Hudson homepage, click New Job.
  • Enter a Job name, for example “Dave’s Product Build” and choose “Build a free-style software project”. Click OK.

Now you need to configure the job; the configuration form should be displayed immidiately after adding.

Under Source Code Management choose Subversion and enter:

  • Repository URL: http://www.myrepo.com/path/to/repo
  • Local module directory: source
  • Check “Use update” which speeds up checkout

Under Build Triggers select Poll SCM and enter the following schedule:

5 * * * *
10 * * * *
15 * * * *
20 * * * *
25 * * * *
30 * * * *
35 * * * *
40 * * * *
45 * * * *
50 * * * *
55 * * * *

Note that this will poll for changes to the repository every 5 minutes and rebuild if any changes are detected.

Under Build click the button to Add build step and choose Execute shell, enter the command:

phing -f $WORKSPACE/source/build.xml prepare app phpdoc phpcs phpunit -Dws=$WORKSPACE

Under Post-build Actions choose:

  • Check Publish Javadoc and then enter:
    Javadoc directory = build/docs/
  • Check Publish testing tools result report and then click Add and pick PHP Unit, enter:
    + PHPUnit Pattern = build/logs/phpunit.xml
  • Check Publish Clover Coverage Report and enter:
    + Clover report directory = build/logs/coverage
    + Clover report file name = clover.xml
  • Check Publish duplicate code analysis results and enter:
    + Duplicate code results = build/logs/phpunit.pmd-cpd.xml
  • Check Publish Checkstyle analysis results and enter:
    + Checkstyle results = build/logs/checkstyle.xml

Finally, click Build Now to test it all works.

posted on Monday 9th November 2009 by Dave

Hello world!

This is indeed my first Wordpress post!  I’ve got the blog setup… now to write some content. 6MV64CZAHU54