Singleton Pattern

The Singleton pattern is a great choice when having more than one instance of a class would be a bad thing, possibly because it would cause resource conflicts or take up too many resources.

Most commonly used in PHP to limit connections to the database throughout the codebase, the Singleton pattern is actually very easy to implement. The following code is a simple implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Database
{
// A static property to hold the single instance of the class
private static $instance;

// The constructor is private so that outside code cannot instantiate
private function __construct() { }

// All code that needs to get and instance of the class should call
// this function like so: $db = Database::getInstance();
public function getInstance()
{
  // If there is no instance, create one
  if (!isset(self::$instance)) {
    $c = __CLASS__;
    self::$instance = new $c;
  }
  return self::$instance;
}

// Block the clone method
private function __clone() {}
}

// To use, call the static method to get the only instance
$db = Database::getInstance();

2 Responses

Subscribe to comments via RSS

  1. Written by Sidney
    on August 24, 2010 at 4:15 pm
    · Permalink

    Great site. Hope you to continue the articles.
    Just a addition here. You’ve forgot to ‘block’ the clone method. You should have added this method:

    private function __clone(){}

    Very good website anyway!
    Bye

    • Written by Eric B
      on August 24, 2010 at 9:53 pm
      · Permalink

      Thanks, Sidney! I’ve updated the code to include your suggestion. I am planning to write more articles, I’ve just been busy with other projects. Hopefully soon, though!

      Eric

Subscribe to comments via RSS

Leave a Reply

You must be logged in to post a comment.