Naming is Hard

Icon

Written by Bruce Boughton

Singleton Pattern in PHP4

The Singleton pattern is an important design pattern in programming. I wanted to implement this in PHP4. I wanted a generic function to store singletons of any type. I also wanted to implement keyed singletons (which for confusion’s sake I named multitons) so that I could store and access objects by their type and a well-known key (such as their primary key in a database).

Here’s what I came up with:

[ftf def="php.xml" w="400"]
function &Singleton($type, $value = null)
{
return Multiton($type, 0, $value);
}

function &Multiton($type, $key, $value = null)
{
static $Multitons = array();

if ($value != null) {
// Setting multiton
if (!isset($Multitons[$type])) {
$Multitons[$type] = array();
}
if (isset($Multitons[$type][$key])) {
die(‘Multiton for type ‘ . $type . ‘, key ‘ . $key . ‘ already set’);
}
else if (!is_a($value, $type)) {
die(‘Multiton cannot be set for type ‘ . $type
. ‘, key ‘ . $key . ‘ as value is not of expected type’);
}
else {
$Multitons[$type][$key] = $value;
return $Multitons[$type][$key];
}
}
else {
if (!isset($Multitons[$type]) || !isset($Multitons[$type][$key])) {
return null;
}
else {
return $Multitons[$type][$key];
}
}
}
[/ftf]

You set a singleton by calling the Singleton function with the type name and the value. For example:

[ftf def="php.xml" w="400" h="80"]
Singleton(‘DB’, &new DB(‘localhost’, ‘user’, ‘pass’, ‘db’));
[/ftf]

You retrieve a singleton by calling the Singleton with just the type name:

[ftf def="php.xml" w="400" h="80"]
$db = Singleton(‘DB’);
[/ftf]

Multitons work similarly but the second required parameter is the key:

[ftf def="php.xml" w="400" h="160"]
Multiton(‘Account’, 435, &new Account(435));

//…

$acc = Multiton(‘Account’, 435);
[/ftf]

There are some oddities which are due to the shortcomings of PHP4. First of all, function parameters with default values cannot be declared to be passed by reference in the function signature, so the pass-by-reference & must be included on the set-call to Singleton/Multiton. Secondly, static variables in functions cannot be assigned by reference. I’m not sure if this means that my singletons and multitons are not stored by reference. If it does, maybe the references could be wrapped so that the wrapper is stored by value but the reference is not? Naughty PHP!

NB: I realise this isn’t exactly a true rendition of the traditional Singleton pattern, but PHP4 isn’t really a proper object oriented language, so I had to bend the pattern a little bit. Could someone remind me exactly why I’m wasting my time in PHP?!

Category: Miscellanea

Tagged:

Comments are closed.