Saturday, May 12, 2007

Design Pattern in PHP Architecture

Singleton pattern defines a class that hs only a single global instance. There are an abundance of places where a singleton is a natural choice. A browsing user has only a single set of cookies and has only one profile. Similarly, a class that wraps an HTTP request has only one instance per request. If you use a database driver that does not share connections, you might want to use a singleton to ensure that only a single connection is every open to a given database at a given time.

One successful method for implementing singletons in PHP5 is to use a factory method to create a singleton. The factory method keeps a private reference to the original instance of the class and returns that on request.

class Singleton {
private static $instance = false;
public $property;

private function __construct () {}
public static function genInstance ()
{
if (self :: $instance === false) {
self :: $instance=new Singleton;
}
return self :: $instance;
}
}

$a = Singleton :: getInstance()
$b = Singleton :: getInstance()
$a ->property = "Hello world";

print $b ->property;

//Amazing! The result will be "Hello world"//

In fact, if set the constructor methods private, you can only make instance inside the class, if you try to instantiate outside the class, you will get a fatal error.

No comments: