WordPress singleton instance practice

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:


       * Placeholder method 	 
       private function __construct() {           

	 * 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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s