In software engineering, a design pattern is a general solution to a common problem in software design. A design pattern isn't a finished design that can be transformed directly into code, it is a description or template for how to solve a problem that can be used in many different situations.
One of these design patterns is called the Singleton. It's purpose can be described quite briefly as follows:
Ensure a class has only one instance and provide a global point of access to it.
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.
<?php
require_once('DB.php');
class DBConn
{
/**
* MySQLI instance
*/
private $_mysqli = null;
/**
* Object instance
*/
private static $_instance;
/**
* The private construct prevents instantiating the class externally
*/
private function __construct() {
$this->_mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
}
/**
* This method must be static, and must return an instance of the object
* if the object does not already exist
*/
public static function getIns()
{
if ( !isset(self::$_instance) ) {
$cls = __CLASS__;
self::$_instance = new $cls;
}
return self::$_instance;
}
/**
* Get mysqli handle
*/
public function getHandle() {
return $this->_mysqli->thread_id;
}
/**
* Other DB operation methods
*/
public function otherMethods() {
// ...
}
}
echo 'Handle = ' . DBConn::getIns()->getHandle() . PHP_EOL;
echo 'Handle = ' . DBConn::getIns()->getHandle() . PHP_EOL;
?>
The UML for this code is simple, and you can draw it yourself without difficulty.
For a more general example, go and have a look at http://php.net
However, we also have another way to realize this pattern:
<?php
class DBConn
{
private static $instance;
public function __construct() {
if (!self::$instance) {
self::$instance = $this;
return self::$instance;
} else {
return self::$instance;
}
}
//keep other methods same
}
?>
You can have tens of "new DBConn", but you actually get only one instance!