Issue no. 3 on design patterns: The singleton pattern.
Whenever we need a place to save and retrieve data throughout a script without using globals the singleton pattern comes in handy. It allows only one instance of itself. What seems like a drawback is quite useful: Wherever in your source you instantiate such an object: You can be sure that you’ll always get the instance of the same object. Remember the parameterized factory from the last chapter? Every time we wanted to create a new database-access-object we had to pass “mysql” or “pgsql” to the create-method. Wouldn’t it be easier if we just saved the database type to a singleton and retrieved it everytime we need it?
//------------------------------------------------ // Singleton //------------------------------------------------ // Definition class Singleton { // "This is a handle to myself" private static $instance; // database type public $dbtype = ""; // Private clone-function and private constructor // make sure, that nobody can clone the object or // instantiate it using the standard constructor. private function __construct() {} private function __clone() {} // This one returns the instance handle to itself. // It's static, because it has to be accessible // before any object is available public static function GetInstance() { // "Am I already existing?" if (!isset(self::$instance)) { // "No? Create myself and save the handle // to myself." $class = __CLASS__; self::$instance = new $class; } // "Return handle to mysqlf" return self::$instance; } } // ... // somewhere in our code function SetupScript() { // Get handle to our singleton object $GlobalInfos = Singleton::GetInstance(); // Set the $content variable to 42 $GlobalInfos->dbtype = "mysql"; } // ... // somewhere else in our code SetupScript(); // ... deep down in the code // Get handle to our singleton object $Registry = Singleton::GetInstance(); // Remeber that from the last chapter? $myDbObj= MyClassFactory::Create($Registry->dbtype);