OOP in PHP 4: Implementing Singleton and Factory Patterns
PHP 4.0 has been out for a while now, and while it's a massive improvement over PHP 3, the object model is... let's say "minimalist." Objects are passed by value, not by reference, and there's no concept of private members or static class variables. However, if you want to build a serious enterprise application (maybe even the next Yahoo!), you need design patterns.
The Singleton Pattern
The biggest challenge in PHP 4 is maintaining a single instance of a class, like a database connection. Since we don't have static properties, we have to use a static variable inside a global function or a class method.
class Database {
var $connection;
function &getInstance() {
static $instance;
if (!isset($instance)) {
$instance = new Database();
}
return $instance;
}
function connect() {
$this->connection = mysql_connect("localhost", "user", "pass");
}
}
// Usage:
$db =& Database::getInstance();
Crucial Note: Notice the & (ampersand). In PHP 4, if you forget the reference operator, PHP will create a copy of your object, and your Singleton will no longer be a Singleton.
The Factory Pattern
Decoupling your code is essential. Instead of hard-coding class names everywhere, use a Factory.
class ImageFactory {
function &create($type) {
switch ($type) {
case 'jpeg':
$obj = new JpegImage();
return $obj;
case 'gif':
$obj = new GifImage();
return $obj;
}
}
}
$factory = new ImageFactory();
$myImage =& $factory->create('jpeg');
The "Zend Engine" Reality
We have to accept that PHP 4 is essentially a procedural language with some "object-oriented" syntactic sugar. Every time you assign $a = $b, you're duplicating memory if they are objects. Always use =& for assignments if you want to work with the same instance. It's ugly, it's error-prone, but it's the only way to write scalable PHP in 2001.
Wait for PHP 5, they say it will have a completely rewritten object model. We'll see.
Aunimeda builds production-grade backend systems - APIs, microservices, real-time applications, and system integrations.
Contact us for backend engineering services. See also: Custom Software Development, Web Development