Tag Archives: code

The Visitor Pattern in PHP

Implementing the Visitor Pattern requires the ability to dynamically determine the type of the Visitor and the type of the “Element” (aka: object receiving the visitor).

In PHP (>= 5.0.0), this can easily be achieved with the get_class() function as we will see shortly.

Let’s start by looking at how the Visitor Pattern will look within user code;

$updateVisitor = new UpdateVisitor();
$deleteVisitor = new DeleteVisitor();
$element = new Foo();


Looking at the UpdateVisitor class, we want the visitFoo() function to be called;

interface Visitor { }
class UpdateVisitor implements Visitor {
    public function visitFoo(Foo $theElement) {
        // ...

You may already be (correctly) thinking “Why not just call $updateVisitor->visitFoo($element) directly?”.
Continue reading

Tagged , , ,

Inserting a function into all classes in a directory via Terminal

Or; Multi-line Search and Replace regular expression on the Command Line.

The situation

You have a single abstract class which is extended multiple times in 10 or 100 different classes throughout your codebase.

You’ve found a need for a new abstract method which all classes must now implement.

The problem

Who wants to manually insert that new code into all those classes!? (I don’t).

We need an automated way to do this
Continue reading

Tagged , , , , , , ,

Zend Framework Quickstart with MySQL

The Zend Framework Quickstart guide is a great place to start with the Framework, however it bases the example program on SQLite. As MySQL is the choice of the rest of the world (and even Zend’s own Stack installation), here is the Zend Framework Quickstart done with MySQL.

Continue reading

Tagged , , ,

PHPUnit Bootstrap and Autoloading classes

The PHPUnit Bootstrap is perfect when there is code to be run before tests are executed. The limitation however is there can only be one bootstrap per PHPUnit configuration file.

This is an issue if there are a set of classes that need to be included – we don’t want to manually include every class every test could possibly need.

PHP’s Autoloading feature comes to the rescue, allowing us to seamlessly include classes as they’re required for tests.
Continue reading

Tagged , , , , ,

Install a Play Framework module from source

The Play Framework provides a great flexible Module system whereby any stand-alone code can be separated entirely from your main application. There are a number of pre-build and ready to go modules available here.

What if you want to check one out from github or googlecode and use it from source? Unfortunately, the Play Framework documentation on this is very sparse, so here’s how:
Continue reading

Tagged , ,