Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 3 ■ SINGLETON AND FACTORY PATTERNS^23

Next are the private __construct() and __clone() magic methods. The private constructor
prevents the object from being created from an external context using the new operator. Similarly,
the private __clone() method closes a small loophole in the PHP language that could make a
copy of the object and defeat singleton responsibility.
Next, the getInstance() static method is declared. This is the real meat of the singleton
pattern. This function checks if the static instance variable already holds an instance of the
class. If it does not contain an instance of itself, the class is instantiated and stored in $_instance.
The next time the code is called, $_instance will hold an instance of the class, and the class will
not be instantiated again. Finally, the reference to the instance is returned.
So, now you’ve seen how to declare the singleton class. But how do you use it? Listing 3-2
demonstrates the use of a singleton class from another context.

Listing 3-2. Using a Singleton Class

$db = Database::getInstance();
$db->query('SELECT * FROM example_table');

By calling getInstance(), $db now holds a reference to the internally stored instance. With
the instance, you can call any non-static method defined in the singleton class.
If your class does not need a __construct() method, the singleton pattern is not appropriate.
In that case, you should use a purely static class. Simply provide a private constructor with no
body and omit the getInstance() and $_instance members. This will prevent instantiation, so
you are assured a single point of responsibility by eliminating the obtaining of an instance when
the code is used. Listing 3-3 shows an example of a purely static class.

Listing 3-3. Using a Purely Static Class That Cannot Be Instantiated

class SomeClass {

//Prevent the class from being used as an instance
private function __construct() {}

public static function SomeMethod() {
//Do something
}

}

The Factory Pattern
Factories are any class that contains a method whose primary purpose is to create another
object. Factories are critically important to the practice of polymorphic programming. They
allow you to substitute classes, change configuration on the fly, and generally make your appli-
cation more nimble. The successful mastery of the factory pattern is important for any advanced
PHP developer.
The factory pattern is typically used to return different classes that conform to a similar
interface. A common use for factories is to create a polymorphic provider, allowing you to

McArthur_819-9C03.fm Page 23 Friday, February 1, 2008 10:24 AM

Free download pdf