.:] patterns.for.php.001-factory [:.
One of the marks of a good language is the ability to apply the principles of Design Patterns to a project written in that language. PHP has come a loooong way in this sense in the jump from PHP3 -> 4 -> 5.
This will be part 1 in a series of unknown length where I will publish simple to use pattern implementations for PHP with examples and downloadable source code. *hooray Blog software update*
Lets start with a basic factory object. Examine the code below:
// First we define our interface for the object we will be working with
interface Auto {
public function go();
}
// Now let's define our implementation classes of Auto
class Ford extends Object implements Auto {
public function __construct() { parent::__construct(); }
public function go() { print("*sputter* *sputter* *cough*"); }
}
class Chevy extends Object implements Auto {
public function __construct() { parent::__construct(); }
public function go() { print("*vrooooooOOoOOOoOoOOom"); }
}
// And finally our factory
final class AutoFactory {
public static function getFord() { return new Ford(); }
public static function getChevy() { return new Chevy(); }
}
// Now lets see what happens
class Main {
public $car;
public function __construct() {
$this->car = AutoFactory::getFord();
$this->car->go();
$this->car = AutoFactory::getChevy();
$this->car->go();
}
}
$running = new Main();
The output from this small program would be as follows:
*sputter* *sputter* *cough* *vrooooooOOoOOOoOoOOom
There you have it, a simple PHP implementation of the Factory pattern — in my opinion, one of the most widely used and important of all Software Design Patterns, especially when practicing dependancy management for you application.
Anyhow, tune in tommorow to find out how to apply the DAO pattern to PHP5 thereby abstracting your Persistance Layer even further from your application and allowing you to change your Database Abstraction libraries (PHP, AdoDB, Pear, etc) and leave your actual data manipulation code alone, as well as your business logic.

