Today we will discuss the Singleton pattern, the most controversial creation pattern.
A Singleton is a global point of access for a resource that must have only one instance in the whole application: database connections, http streams, and similar objects are the typical examples of such a class.
This behavior is implemented trough a static method which returns a lazy-created instance, and by rendering the constructor private to avoid creation of an instance from outside the class code.
This is a simple example of a singleton implementation:
<?php class PR_SINEXAMPLE { /** * Placeholder method */ private function __construct() { $this->setup(); } /** * Get a singleton instance of the class */ public static function factory() { static $instance = false; if ( ! $instance ) { $instance = new self(); } return $instance; } /** * Setup actions and filters */ public function setup() { } } global $pr_singleton; $pr_singleton = PR_SINEXAMPLE::factory();
The problems of a Singleton class are the same of its non object-oriented equivalent: a global variable. The Api of Clients of the Singleton lies, because they do not declare in any signature that they are taking advantage of the Singleton’s capabilities; moreover, global mutable state is introduced and encapsulation is disregarded.