Using SQL Server ntext Columns In PHP

I had to connect to a SQL Server database from a PHP script earlier, and I came across an error I wasn’t expecting.

My SQL was working fine, until I tried to select one particular column, it would then give me a 4004 error. Other columns in this table worked fine, so I investigated more.

The error string returned with the 4004 error code was “Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.”

Looking at the table definition, the column I was trying to SELECT was of type ntext. This is used to hold UTF-8 data.

By default the driver I had installed for PHP on Ubuntu Linux using

apt-get install php5-sybase

couldn’t understand this UTF-8 data. The solution is to edit the conf file used by freetds, which is the code used to talk to the SQL Server database by the PDO DBLib library.

So, in /etc/freedts/freetds.conf I added these settings

[global]
tds version = 8.0
client charset = UTF-8

After adding those settings, I was successfully able to SELECT the ntext column from the SQL Server database.

Unit Testing JavaScript With QUnit And Phing

Recently I’ve been using both Phing for my PHP builds, and QUnit for my JavaScript unit tests, so I’ve been looking for a way to run these QUnit tests when Phing builds my application.

By default Phing can run PHPUnit tests, but not QUnit. However Martin Jonsson has come to the rescue with his Qunit Phing Task.

QUnit Phing Tasks lets QUnit tests be run during a build and Phing can either pass or fail based on these results. As QUnit is written in JavaScript, QUnit Phing Task runs PhantomJS to call a JavaScript wrapper that passes the output back to PHP and Phing. PhantomJS is a headless JavaScript browser that can excute on a command line.

Using QUnit Phing Task

To run the QUnit Phing Task you need to install PhantomJS. I downloaded a binary and placed it in /usr/local/bin on my system.

You need to download the QUnit Phing Task. I placed the files in a local ./lib directory in my project.

You will also need to download QUnit. I placed the files in a local ./tests directory in my project.

In the ./tests directory I created an HTML file called runner.html. This is the page we need to call to run our tests.

<!DOCTYPE html>

<html>
        <head>
                <meta chatset="utf-8" />
                <title>Qunit Tests</title>
                <link rel="stylesheet" href="./qunit.css">
                <script src="./qunit.js"></script>
                <script src="./test.js"></script>
        </head>

        <body>
                <div id="qunit"></div>
        </body>
</html>

I also create a JavaScript file called ./test.js in ./tests to hold my JavaScript tests in.

test("testing for true", function() {
        ok(true, "true is true");
});

Finally, I create a build.xml for my Phing build.

<?xml version="1.0" encoding="UTF-8"?>
<project name="qunit example" basedir="." default="qunit">

        <path id="project.class.path">
                <pathelement dir="./lib/" />
        </path>

        <taskdef name="qunit" classname="QunitTask">
                <classpath refid="project.class.path" />
        </taskdef>

        <target name="qunit" description="JavaScript Unit Test">
                <qunit executable="DISPLAY=:0 /usr/local/bin/phantomjs" haltonfailure="true" runner="./lib/run-qunit.js">
                        <fileset dir=".">
                                <include name="tests/runner.html" />
                        </fileset>
                </qunit>
        </target>

</project>

In this I am specifying a path to my ./lib directory as this is where the QUnit Phing Task code is. The path is then used in the taskdeftask which is used to create the <qunit> task. Now when I call <qunit> in my qunit target I just pass in the location of the executable – in this case where PhantomJS is, whether Phing should halt if the QUnit tests fail, and where to find the the JavaScript that runs QUnit. Inside the task, we pass in where our runner pages are, as we only have the one in this example we include it by name tests/runner.html.

Running this gives us the following…

rob@lamp ~/qunitphing> phing
Buildfile: /root/qunitphing/build.xml

qunit example > qunit:

    [qunit] ./tests/runner.html: 1 tests of 1 passed, 0 failed

BUILD FINISHED

Total time: 0.3275 seconds

So we can see our tests have passed. Let’s change our test.js so that it fails.

test("testing for true", function() {
        ok(true, "true is true");
        ok(false, "false is true");
});

This test should fail, as false is not true and will fail the ok assertion.

rob@lamp ~/qunitphing> phing
Buildfile: /root/qunitphing/build.xml

qunit example > qunit:

    [qunit] 1 tests failed on: ./tests/runner.html
    [qunit] Failed test: testing for true (1, 1, 2)
Execution of target "qunit" failed for the following reason: /root/qunitphing/build.xml:13:41: QUnit tests failed

BUILD FAILED
/root/qunitphing/build.xml:13:41: QUnit tests failed
Total time: 0.3258 seconds

So we can see that Phing has failed our build due to the QUnit tests failing, which is what we want.

Summary

Although a very simple and contrived example, I hope this has shown you how to add JavaScript unit tests using QUnit to your Phing build.

Using Phing To Deploy A PHP Project

Deploying a PHP project to a production or even a staging environment isn’t always as simple as copying a directory. One project I have been working on recently has benefited from using Phing as a deployment system. To deploy my code, I just have to call a single build script, and let Phing do all the hard work.

So what is Phing? Well Phing is a tool based on Apache Ant, specifically designed to build PHP projects. It takes an XML file that defines specific tasks and executes them. It is designed to be platform independent so should be at home running on Windows as well as Unix based systems.

Phing is available using PEAR, and can be installed quickly using the following commands…

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

Hello World! In Phing

It wouldn’t be an overview without a Hello World example. Save the following as build.xml.



    
        
    

Now let’s run this, we just call phing on the command line, and we get something like this back.

rob@lamp /tmp/helloworld> phing
Buildfile: /tmp/helloworld/build.xml

helloworld > helloworld:

     [echo] Hello World!

BUILD FINISHED

Total time: 0.0487 seconds

rob@lamp /tmp/helloworld>

So what is going on? Well in the project element we have a default setting of “helloworld”. This tells Phing the target to call by default. We can call this on the command line as well, phing helloworld, so if we have multiple tasks we can create a target for each of those. As you can see we only have a target of “helloworld” in our example. Inside the target we have tasks. In this example, we have a single EchoTask that just prints out the message “Hello World!”.

Adding A Clean Up

There is so much more Phing can do that just print Hello World!. One of the common tasks you may have is to cleanup a deployment directory. Let’s assume you have a build directory, when you call phing clean you want this to be removed. We can add a simple task to do this to our build.xml.



    
            

As you can see, as well as adding a target called “clean”, I’ve also added a property called “builddir” with the value “./build”. I can access this later as variable, so when I call the DeleteTask, I can reference this value using ${builddir}, and Phing will delete the directory ./build.

Create an empty directory called build and run this using phing clean.

rob@lamp /tmp/helloworld> phing clean
Buildfile: /tmp/helloworld/build.xml

helloworld > clean:

     [echo] Clean...

BUILD FINISHED

Total time: 0.0493 seconds

rob@lamp /tmp/helloworld>

When you check the contents of your working directory you should have found the build directory has been deleted.

Adding A Deployment Target

Deployment is the area where Phing really comes into it’s own. Let’s create a target that creates a build directory then uploads the contents of that via FTP to a remote server.


    
    
    
    
        
            
            
            
            
            
        
    

    
    
        
            
        
    

    

We’re doing a few things here, first we are deleting the ${builddir}, and creating it from scratch to ensure it is clean. Then we are copying all the files in the current directory across, except for the build directory, any build file with any extension, the docs directory and the tests directory. Then we are FTP’ing up the contents of the ${builddir} using a FTPDeployTask. Assume I have already set a selection of FTP variables earlier using the same syntax as earlier when I defined ${builddir}.

OK, so that is useful, but there are other useful things that could be done as part of the process. We may want our JavaScript minified on production, but not when we are developing. We can add a task to do this as part of the deploy using the JSMinTask.

There are plenty of other tasks that can be usefully integrated, such as running phpcs to ensure your code is meeting coding standards, building your documentation using phpdocumentor, running your phpunit unit tests. If anything fails you can prevent the deployment and stop your site breaking unnecessarily.

Summary

This has just been a quick overview of how to use Phing. We’ve seen various simple tasks take place, and we’ve seen we can easily add more tasks to increase functionality and usefulness. In the real world adding tests to check your code before it gets deployed is essential and prevents silly errors hitting your production environment. Taking the time to write a build script will also save you time in the future when you come to make changes to your site and you can’t quite remember how your production environment was setup. Using Phing, you just have to run your build script.

Recursive Functions In PHP

Recursive functions can be very useful when developing in PHP.

A recursive function is simply a function that calls itself, but why would you want your function to be able to call itself?

They are best used when a problem needs to be solved by breaking it up into a smaller instance of itself. Examples of this would be calculation a factorial or the Fibonacci Series.

Let’s take a look at the Fibonacci Series as an example. The series looks like this…

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

It can be described using the following formula,

Fn = Fn-1 + Fn-2

with the seed values,

F0 = 0, F1 = 1

As you can see in the formula’s definition, it has to call itself for n-1 and n-2 to work out the current value for n.

So how would we write this in PHP?

A simple function like this should do the trick.

function fib($n) {
	if ($n < 0) {
		return NULL;
	} elseif ($n === 0) {
		return 0;
	} elseif ($n === 1 || $n === 2) {
		return 1;
	} else {
		return fib($n-1) + fib($n-2);
	}	 
}

As you can see I have added some guard statements, so if $n is 0, we return NULL (as the Fibonacci series starts at 0 and works up from there), for 0 we know the seed value is 0 and for 1 and 2 we know the seed values are 1. As we now know the start of the series, we can call our function to work out any part of the series.

For very large values of $n, there will be a lot of recursion, and this could use a lot of computer resources. Each call to fib (apart from to values 0, 1 & 2) costs us at least two more calls to fib, and these calls could be making more calls as it recurses. For example, when $n is 19, there would be 8361 calls made to the fib function to calculate the result, and when $n is 29, there would be 1028457 calls. It’s easy to see that although this is a very simple formula, it can end up being very expensive to use.

However, we can optimise the code and make things easier. We are constantly calculating the same values multiple times, so this should be telling you that this is an ideal candidate for caching.

Let’s modify our function to keep already calculated values of $n in an array and return those if possible rather than recalculating each call.

function fib($n) {
	static $cache;

	if ($n < 0) {
		return NULL;
	} elseif ($n === 0) {
		return 0;
	} elseif ($n === 1 || $n === 2) {
		return 1;
	} else {
		if (!(!is_null($cache) && array_key_exists($n, $cache))) {
			$cache[$n] = fib($n-1) + fib($n-2);
		}
		return $cache[$n]; 
	} 	
}

Here we are using a static variable to persist the $cache between calls. Then before recursively calling the fib function we check if the $cache isn’t null and if the $cache has data stored with the key value of $n. If it doesn’t we calculate the can cache the data. Finally we return the value from the cache.

Now when we call the function for when $n = 19, our function is only called 35 times, and for $n = 29, our function is only called 55 times. That’s saved us 1028402 calls!

I hope this has been a useful quick look at recursive functions using PHP.

JSON Config Files In Zend Framework

During a recent code review it was suggested that we should move from using an ini file to a JSON file for our Zend Framework application config file. The reason was to reduce duplication of data that can occur and instead move to a nicely nested file.

I wasn’t aware that JSON format config files were supported, but sure enough after a quick look at the Zend Framework documentation, there was the relevant class, Zend_Config_Json. It has only appeared in recent versions of the Zend Framework so that could be why I had missed it.

It’s easy to use in code, being almost a complete drop in for a the usual ini config.

$config = new Zend_Config_Json(
  './example_config.json',
  'production'
);

The first parameter is the location of the config file, the second is the section of the config file to use.

There is an optional third paramter that allows some addition configuration options to be specified such as changing the immutability of the config object once loaded, changing the behaviour of _extends, and the ability to ignore constants. More details can be found in options section of the Zend_Config_Json manual.

Here’s a quick example. Firstly the JSON configuration file.

{
  "production" : {
    "username" : "Robert Price",
    "beer" : [
      "Harveys Sussex Best",
      "Spitfire",
      "Asahi"
    ]
  },
  "testing" : {
    "_extends" : "production",
    "beer" : [
      "Harveys Star Of Eastbourne",
      "Schwaben Brau - Das Helle",
      "Brauhaus J.Albrect - Dunkel"
    ]
  }
}

OK, it’s a good real life example, but it has two sections, production and testing. Testing inherits from production by using the _extends parameter.
We can load and extract details using the following code.

$config = new Zend_Config_Json(
  './example_config.json',
  'production'
);
echo "Username is " . $config->username . "n";
echo "Favourite beers are...n";
foreach ($config->beer as $beer) {
  echo "* " . $beer . "n";
}

When you run this code you get the following results, assuming you saved the json config file from earlier as example_config.json

Username is Robert Price
Favourite beers are...
* Harveys Sussex Best
* Spitfire
* Asahi

Now change the code so instead of production when we load the config file, we use testing. Run the code and you’ll get the following…

Username is Robert Price
Favourite beers are...
* Harveys Star Of Eastbourne
* Schwaben Brau - Das Helle
* Brauhaus J.Albrect - Dunkel

As you can see my username has been inherited from the production block, but the list of beers has changed. This is a very powerful feature that lets you change a small section of data between environments in real code without having to repeat yourself and reduces the risk introducing errors in duplicated config options.

Adding Colour To A Mandelbrot Set

I was looking for a way to introduce some colour into my example Drawing A Mandelbrot Set With Zend PDF.

The method I settled upon was to use HSV – Hue, Saturation, Value.

I’m not an expert on colour theory, so I may not be the best person to describe how it works. The best way I can though, is to describe it as a cylinder, round the circumference is the hue, the radius is the saturation, and the height is the value. For a detailed definition, read the Wikipedia entry on HSL and HSV.

I can pick a hue and value, then just vary the saturation to give a nice graduated colour version of the earlier grayscale example.

Blue Mandelbrot

Alternatively I can pick a value and saturation, and vary the hue to give a vivid rainbow style fractal.

Vivid Mandelbrot

To achieve the first, we replace the code in the loop that prepared the grayscale colours, and instead generate our $colours array with the following…

list($red, $green, $blue) = hsvToRgb(0.5, $grayLevel, 1);
$colours[$i] = new Zend_Pdf_Color_Rgb($red, $green, $blue);

Firstly we get the values for $red, $green and $blue for a hue of 0.5 (blue), our varying $graylevel between 0 and 1, and a $value of 1 for the most vivid colours. After this we create a Zend_Pdf_Color and store it in the $colours array to use later.

To achieve the latter we just change how we call the hsvToRgb function.

list($red, $green, $blue) = hsvToRgb($grayLevel, 1, 1);
$colours[$i] = new Zend_Pdf_Color_Rgb($red, $green, $blue);

Now, you may have noticed that there isn’t a function called hsvToRgb available to PHP. Just drop in the following code.

function hsvToRgb ($hue, $saturation, $value)
{
  $rgb = array($value, $value, $value);
  if ($saturation != 0) {
    $varH = $hue * 6;
    $varI = floor($varH);
    $var1 = $value * ( 1 - $saturation );
    $var2 = $value * ( 1 - $saturation * ( $varH - $varI ) );
    $var3 = $value * ( 1 - $saturation * (1 - ( $varH - $varI ) ) );
    if ($varI == 0) {
      $rgb = array($value, $var3, $var1);
    } else if ($varI == 1) {
      $rgb = array($var2, $value, $var1);
    } else if ($varI == 2) {
      $rgb = array($var1, $value, $var3);
    } else if ($varI == 3) {
      $rgb = array($var1, $var2, $value);
    } else if ($varI == 4) {
      $rgb = array($var3, $var1, $value);
    } else {
      $rgb = array($value, $var1, $var2);
    }
  }
  return $rgb;
}

Drawing A Mandelbrot Set With Zend PDF

As you may know from some of my previous posts, I’ve been looking at Zend Framework’s PDF support.

As a bit of fun on the train home from work, I wondered if it would be possible to draw out a Mandelbrot Set using the PDF drawing functions in Zend_Pdf.

For those who don’t know what the Mandelbrot Set is, it is a fractal shape, and one of those projects every developer plays with at some point. It looks like my time has come here.

There is a reasonably simple formula for generating the image, we just need to iterate between a maximum and minimum x and y co-ordinate set and draw a pixel at each point when the number of iterations of the formula has reached a pre-defined number. In my example, I’m using 20 iterations, though you can go higher for greater accuracy. I won’t go over the formula, as it is explained in far greater depth than I have time for elsewhere on the internet.

In this code example, I’m using variables similar to those used in Mandelbrots formula, so they do trigger warnings with Zend Framework’s coding standards, but I think they make sense.

// load the Zend Framework Autoloader.
ini_set('include_path', './library');
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$maxIterations = 20;
$minX = -2;
$maxX = 1;
$minY = -1;
$maxY = 1;
try {
  // create a new PDF document.
  $pdf = new Zend_Pdf();
  // create a new A4 sized page.
  $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
  // calculate the width and height of the image to generate.
  $width = $page->getWidth();
  $height = $page->getHeight();
  if ($width > $height) {
    $width = $height;
  } else {
    $height = $width;
  }
  // prepare a black colour we can reuse when we draw the mandelbrot set.
  $black = new Zend_Pdf_Color_Html('#000000');
  // iterate over the mandelbrot set and draw it out.
  for ($x=0; $x<=$width; $x++) {
    for ($y=0; $y<=$height; $y++) {
      $c1 = $minX + ($maxX - $minX) / $width * $x;
      $c2 = $minY + ($maxY - $minY) / $height * $y;
      $z1 = 0;
      $z2 = 0;
      for ($i=0; $i<$maxIterations; $i++) {
        $newZ1 = $z1 * $z1 - $z2 * $z2 + $c1;
        $newZ2 = 2 * $z1 * $z2 + $c2;
        $z1 = $newZ1;
        $z2 = $newZ2;
        if ($z1 * $z1 + $z2 * $z2 >= 4) {
          break;
        }
      }
      // if we reach max iterations, draw a black pixel
      if ($i >= $maxIterations) {
        $page->setFillColor($black)
             ->setLineColor($black)
             ->drawRectangle(
               $x,
               $y,
               $x+1,
               $y+1,
               Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE
             );
      }
    }
  }
  // add the page to the pdf document.
  $pdf->pages[] = $page;
  // save the finished PDF to a file
  $pdf->save('fractal.pdf');
  // catch any errors
} catch (Zend_Pdf_Exception $e) {
  die('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
  die ('Error: ' . $e->getMessage());
}

You will need to run this code on the command line, and it will take a few seconds to execute. When complete, you will have a PDF document with the following image.

Mandelbrot set rendered from a PDF

We can refine this slightly to get a prettier picture if we show the number of iterations used in a different colour, instead of just showing black if we go over our limit of maximum iterations.

To do this, we’d need to prepare an associative array with a colour for each iteration. The easiest option is to use grayscale and Zend_Pdf_Color_GrayScale. After we work out the max width and height, insert the following code.

// prepare colours
for ($i=0; $i >= $maxIterations; $i++) {
  $grayLevel = $i / $maxIterations;
  $colours[$i] = new Zend_Pdf_Color_GrayScale($grayLevel);
}

Now we have an associative array to look up a different shade of gray from 0 to $maxIterations.

Instead of the code that checks if $maxIterations has been reached and then draw a black pixel, we can replace it with the following

$page->setLineColor($colours[$i])
     ->setFillColor($colours[$i])
     ->drawRectangle($x, $y, $x+1, $y+1, Zend_Pdf_Page::SHAPE_DRAW_FILL_AND_STROKE);

Run this modified script on the command line, and you’ll generate a PDF with the following image.

Mandelbrot set rendered from a PDF in grayscale

That image looks great, but not very colourful. I’ll cover how to get some colour in there another time.

Drawing A Image In A PDF With Zend Framework

I recently wrote about Creating A Simple PDF With The Zend Framework, and so I thought I’d take a quick look at Zend_PDF’s Drawing Methods.

As you may know I work for a company called Bauer and we have a very simple logo. It’s basically a blue square, with a gray triangle in the top right hand corner and the name BAUER in white at the bottom. This sounds like an ideal image to try to recreate using Zend_PDF.

Bauer Media Logo

Take a look at my previous article on PDF’s and Zend Framework for an explanation of setting up a document and page to draw on. I will assume this page has been setup and is available in the $page variable.

Firstly we need to prepare a font for use. I don’t know the font Bauer use, so I’ll just use Helvetica Bold in this example.

$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);

The background is a blue square, so I need to set the fill colour to the shade of blue Bauer use, then draw the square using this colour.

$page->setFillColor(new Zend_Pdf_Color_Html('#014495'))
     ->drawRectangle(0, 0, 200, 200, Zend_Pdf_Page::SHAPE_DRAW_FILL);

As you can see, I’ve decided to make the logo 200×200 in size.

Now it’s time to write BAUER at the bottom in white using the font we prepared earlier.

$page->setFillColor(new Zend_Pdf_Color_Html('#ffffff'))
     ->setFont($font, 52)
     ->drawText('BAUER', 7, 10);

Firstly I set the fill colour to white. Next I select the font and set it’s size. Finally I write the word BAUER at co-ordinates 7,10, which happens to be at the bottom of the blue square.

Finally it’s time to draw the gray triangle in the top right corner of the blue square.

$page->setFillColor(new Zend_Pdf_Color_Html('#dddddd'))
     ->drawPolygon(array(70, 190, 190),
                   array(190, 190, 70),
                   Zend_Pdf_Page::SHAPE_DRAW_FILL);

As before, I set the fill colour, this time to gray. Now I use the drawPolygon method to draw the triangle. As you can see there are two arrays there, the first are the x co-ordinates of the triangle, the second are the y co-ordinates of the triangle. The fill method is the last parameter, it’s the same as the one we used when drawing the blue square.

We should now have our Bauer logo on the page!

generated copy of the Bauer Media logo

I don’t think that Bauer will be sacking their design team in a hurry, but it’s quite a close approximation of the logo.

Here’s a copy of the finished code.

// load the Zend Framework Autoloader.
ini_set("include_path","./library");
require_once 'Zend/Loader/Autoloader.php';

$loader = Zend_Loader_Autoloader::getInstance();

try {
  // create a new PDF document.
  $pdf = new Zend_Pdf();

  // create a new A4 sized page.
  $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);

  // prepare the Helvetica Bold font.
  $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA_BOLD);

  // draw the blue square background.
  $page->setFillColor(new Zend_Pdf_Color_Html('#014495'))
       ->drawRectangle(0, 0, 200, 200, Zend_Pdf_Page::SHAPE_DRAW_FILL);

  // draw the white BAUER text at the bottom of the square.
  $page->setFillColor(new Zend_Pdf_Color_Html('#ffffff'))
       ->setFont($font, 52)
       ->drawText('BAUER', 7, 10);

  // draw the grey triangle in the top right corner of the square.
  $page->setFillColor(new Zend_Pdf_Color_Html('#dddddd'))
       ->drawPolygon(array(70, 190, 190),
                     array(190, 190, 70),
                     Zend_Pdf_Page::SHAPE_DRAW_FILL);

  // add the page to the pdf document.
  $pdf->pages[] = $page;

  // save the finished PDF to a file
  $pdf->save('bauer.pdf');

// catch any errors
} catch (Zend_Pdf_Exception $e) {
  die('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
  die ('Error: ' . $e->getMessage());
}

Creating A Simple PDF With The Zend Framework

I’ve recently been playing with creating PDF documents for a project I’ve been working on.

I thought I’d share some of the knowledge I’ve gained in the hope it will help others.

I’ve been using the excellent Zend Framework as usual, and the Zend_Pdf component in particular. This is a pure PHP implementation of the PDF standard and it doesn’t require any other libraries to be installed to work.

A PDF document is text document that has been been designed by Adobe a way to create and share printable documents across multiple platforms. If you open a PDF document in a text editor, you can see the markup for yourself, however it’s not very user friendly. This is where Zend_Pdf comes to our aid.

Let’s create a simple A4 document, and say Hello World!.


<?php
// load the Zend Framework Autoloader.
ini_set("include_path","./library");
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
try {
// create a new PDF document.
$pdf = new Zend_Pdf();
// create the Helvetica font.
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// create a new A4 sized page.
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
// draw the text Hello World! to position 0,0 with the Helvetica font.
$page->setFont($font, 16)
->drawText('Hello World!',0,0);
// add the page to the pdf document.
$pdf->pages[] = $page;
// save the finished PDF to a file
$pdf->save('helloworld.pdf');
// catch any errors
} catch (Zend_Pdf_Exception $e) {
die('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Error: ' . $e->getMessage());
}
?>

What’s going on? Well firstly I take advantage of Zend Frameworks autoloader to load in the required components.

Next I create an empty PDF document. A copy of the Helvetica font is prepared for use. We’ll need to add pages to this document, so after this we create a new A4 sized page. I’ve used A4 as that is the common paper size in Europe, but in the US letter size is the standard. This can be changed by using Zend_Pdf_Page::SIZE_LETTER instead of Zend_Pdf_Page::SIZE_A4.

Now I have a page, I want to add some text to it. This is easily achieved using the drawText method. This takes the text, and an X and Y position to draw it at. We do need to set the font first, let’s use the Helvetica font we defined earlier, and use size 16. I chose position 0,0 to write the text, this is the bottom left hand side of the page.

Finally, I add the page to PDF document, and save it.

If an error occurs, I catch this with my exception handlers.

Of course, in reality you’ll want o do a lot more than just write one line of text. Zend_Pdf allows you to do a lot more, such as adding images, drawing graphics, adding meta data. I’ll cover this in another post.

Using The Cycle Function In Twig

I was looking at adding zebra stripes to some data to improve readability to a page of data generated from PHP using the Twig templating system.

Twig provides a method called cycle that can be used to alternate through a list of values, so this is was the obvious candidate.

cycle takes 2 parameters, the first is an array of values to iterate through, the second is an integer with the cycle value.

This means all I have to do is to pass in an array with the css class names I’m using for my striping, and the position of the loop I’m iterating through to display my data. For example…

 
{% if users|length > 0 %}
  <ul>
{% for user in users %}
  <li class="{{ cycle(['even','odd'],loop.index) }}">{{ user.username|e }}</li>
{% endfor %}
  </ul>
{% endif %}

I have a list of users that I’m iterating through. For each user I choose wether to display use either the odd or even class using the cycle function. I have to pass in loop.index as the cycle value to count as this increments each time the loop is iterated through.

This gave me an output something like this…

 
<ul>
  <li class="even">Rob</li>
  <li class="odd">John</li>
  <li class="even">Paul</li>
  <li class="odd">George</li>
  <li class="even">Ringo</li>
</ul>