Utilizing the Singleton Design Pattern
A Design Pattern is a commonly used block of code that can be used to solve a common problem.
The singleton design pattern is used to solve the issue of having multiple instances of a class where you only need 1, for say a DB wrapper class.
The Singleton Design Pattern Example:
[highlight=PHP]
<?php
class MyClass {
static $instance = null;
function MyClass() { }
static function getInstance() {
if (self::instance == null) {
self::instance = new MyClass;
}
return self::instance;
}
}
?>
[/highlight]
Note: If you are using PHP5, you may replace 'function MyClass()' with 'public function __construct()'
Okay, lets break it down line-by-line.
Line 2: Class declaration of the class 'MyClass'
Line 3: Definition of the static variable $instance (the variable is static so the value will not change no matter the instance) which is defaulted to null. This variable is used to hold the current instance of the class.
Line 4: A definition of the class constructor which overrides any actions to be performed on instantiation.
Line 6: Function definition of the static function 'getInstance()' (The function is static so we do not need an instance to call)
Line 7: Checks to see if the the static variable (referenced using the self::STATIC_VARIABLE_NAME syntax) contains an instance or not (null).
Line 8: If it is set to null (no instance), then the function creates a new instance of the 'MyClass' and stores that in the variable.
Line 10: Returns the current value of the self::instance variable.
Condensed: Instead of creating a new instance of the class, you call this static function and decides whether or not to give you a new instance or the class or retrieve a stored one.
To use this design pattern, you follow the example:
PHP Code:
<?php
include('/path/to/class/file.php');
$MyClass = MyClass::getInstance();
?>
The code above includes the MyClass class definition file and then assigns a variable to the return value of getInstance();
To show that the code above is correct, the following code should output 'True':
PHP Code:
<?php
include('/path/to/class/file.php');
$MyClass = MyClass::getInstance();
if ($MyClass instanceof MyClass) {
echo "True";
}
?>
Thank You For Reading This Tutorial, I hope you enjoyed it!
-Rick
Last edited by Nick Presta; 09-18-2006 at 03:34 PM.
"Yeah, so, umm.., I wanted to get my girlfriend out of work so I called in a bomb threat, but I got caught..."
From 104.1's 'It seemed like a good idea at the time' segment