Our First Build Script

A task that can and should be automated in a build script (because it makes no sense to perform such a task at runtime) is the generation of code for an autoloader. Example 1-1 uses this task to show he essence of writing a build script for use with Ant.

 

Each project defines one or more targets. A target is a set of tasks you want to be executed. When starting Ant, you can select which target(s) you want to have executed. When no target is given, the project's default is used. [...] A target can depend on other targets. [...] Ant resolves these dependencies. [...] A task is a piece of code that can be executed.

 
 --http://ant.apache.org/

Example 1-1. build.xml script that invokes phpab

<?xml version="1.0" encoding="UTF-8"?>

<project name="BankAccount" default="build">
 <target name="build" depends="phpab"/>

 <target name="phpab" description="Generate autoloader scripts">
  <exec executable="phpab">
   <arg value="--output" />
   <arg path="${basedir}/src/autoload.php" />
   <arg value="--template" />
   <arg path="${basedir}/build/src_autoload.php.in" />
   <arg path="${basedir}/src" />
  </exec>

  <exec executable="phpab">
   <arg value="--output" />
   <arg path="${basedir}/tests/autoload.php" />
   <arg value="--template" />
   <arg path="${basedir}/build/tests_autoload.php.in" />
   <arg path="${basedir}/tests" />
  </exec>
 </target>
</project>

In the build script above, we first define a build target. This target does not perform any task by itself but rather depends on other targets, so far only phpab. You can think of this as a meta target that orchestrates other targets.

The phpab target uses the <exec> task to invoke the aforementioned PHP Autoload Builder to generate the autoloader code. The two <exec> tasks are equivalent to calling phpab on the command-line like so:

phpab --output src/autoload.php --template build/src_autoload.php.in src
phpab --output tests/autoload.php --template build/tests_autoload.php.in tests

Invoking Ant in the directory that holds our build.xml file will now run the build target and its dependencies:

ant
Buildfile: /home/sb/bankaccount/build.xml

phpab:
     [exec] Autoload file 'src/autoload.php' generated.
     [exec]
     [exec] Autoload file 'tests/autoload.php' generated.
     [exec]

build:

BUILD SUCCESSFUL
Total time: 0 seconds

A useful option for Ant is -projecthelp. It prints project help information based on the description attribute of the target elements in the build.xml:

ant -projecthelp
Buildfile: /home/sb/bankaccount/build.xml

Main targets:

 phpab  Generate autoloader scripts
Default target: build

Targets that do not have a description attribute are considered private and are excluded from the -projecthelp output.