Showing posts with label singleton pattern. Show all posts
Showing posts with label singleton pattern. Show all posts

Saturday, May 23, 2009

The singleton pattern using PHP

Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it's an overhead to keep opening and closing connections, particularly during a single page fetch.
The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time. The code below shows a database connection singleton in PHP5.

Singleton.php

<?php
require_once("DB.php");

class DatabaseConnection {
public static function get() {
static $db = null;
if ( $db == null )
$db = new DatabaseConnection();
return $db;
}

private $_handle = null;

private function __construct() {
$dsn = 'mysql://root:password@localhost/photos';
$this->_handle =& DB::Connect($dsn, array());
}

public function handle() {
return $this->_handle;
}
}

print("Handle = ".DatabaseConnection::get()->handle()."\n");
print("Handle = ".DatabaseConnection::get()->handle()."\n");
?>


This code shows a single class called DatabaseConnection. You can't create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method.