Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^22) CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS
Unlike a normal class, a singleton class cannot be directly instantiated within other classes.
Instead, a singleton class may instantiate only itself. To achieve this restriction, the construct()
method must be marked private. If you try to construct a class with a private constructor, you
will get an accessibility level error.
To be useful, a singleton class must provide other classes with an instance on which they
can call methods. Instead of creating a copy of the instance, a singleton class will return a refer-
ence to the instance the singleton has stored internally. The result is that the singleton class
prevents duplication of memory and resources that would be better used in another area of
your application. As part of the pattern, you must also prevent an object from being copied or
cloned by creating a blank, private
clone() method.
The method that returns the instance reference is commonly named getInstance(). This
method must be static and must instantiate the class if it has not already been instantiated. The
getInstance method detects if the class has been initialized by utilizing the instanceof operator
and the self keyword. If the static member that holds the instance is null or is not an instance
of the class itself, then an instance will be created and stored to the instance holding variable.
Listing 3-1 shows an example of a singleton class designed to encapsulate a database
connection object.
Listing 3-1. Centralizing Database Connection Responsibility
class Database {
private $_db;
static $_instance;
private function __construct() {
$this->_db = pg_connect('dbname=example_db');
}
private __clone() {};
public static function getInstance() {
if(! (self::$_instance instanceof self) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql) {
//Run a query using $this->_db
return pg_query($this->_db,$sql);
}
}
This example begins with the declaration of two variables: an instance variable $_db, that
will be populated when the object is constructed, and a static variable $_instance, which will
hold the only instance of the class.
McArthur_819-9C03.fm Page 22 Friday, February 1, 2008 10:24 AM

Free download pdf