Design patterns are nothing more than streamlined solutions to common problems. In fact, design patterns are not really about code at all—they simply provide guidelines that the developer, can translate into code for pretty much every possible language.
The Singleton Pattern
The Singleton is, probably, the simplest design pattern. Its goal is to provide access to a single resource that is never duplicated, but that is made available to any portion of an application that requests it without the need to keep track of its existence. The most typical example of this pattern is a database connection, which normally only needs to be created once at the beginning of a script and then used throughout its code. Here’s an example implementation:
class DB {
private static $_singleton;
private $_connection;
private function__construct()
{
$this->_connection = mysql_connect();
}
public static function getInstance()
{
if (is_null (self::$_singleton)) {
self::$_singleton = new DB();
}
return self::$_singleton;
}
}
$db = DB::getInstance();
Our implementation of the DB class takes advantage of a few advanced OOP concepts that are available in PHP 5: we have made the constructor private, which effectively ensures that the class can only be instantiated from within itself. This is, in fact, done in the getInstance() method, which checks whether the static property $_connection has been initialized and, if it hasn’t, sets it to a new instance of DB. From this point on, getInstance() will never attempt to create a new instance of DB, and instead always return the initialized $_connection, thus ensuring that a database connection is not created more than once.
0 Comment to " PHP - Singleton Design Patern Theory "
Post a Comment