Wednesday, March 25, 2015

Singleton Design Pattern in PHP Example

Singleton Pattern
Hello! As we all know that, design patterns used to solve any issue in software engineering. All of design patterns have typical skills. For example, in the singleton pattern a class can distribute one instance of itself to other classes. In this article I'll show you how to design a PDO database class using singleton design pattern in PHP programming language.





//singleton design pattern
class DB {
 
 private static $status = NULL;
 private static $info = 'mysql:host=localhost;dbname=dbname';
 private static $username = 'username';
 private static $password = 'password';
 
 private function __construct() { }
 
 public static function connect() {
  if(!self::$status) {
   try {
    self::$status = new PDO(self::$info, self::$username, self::$password);
    self::$status->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    self::$status->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   }
   catch (PDOException $e) {
    throw new Exception($e->GetMessage()); 
   }
  }
  return self::$status;
 }
 
 public function __destruct() {
  self::$status = NULL; 
 }
}

First, We define status as a static variable, because we want to control whether connection is exists via only one variable. Aftet that define database information as private static variables. After all we create our connection static function, that is connect().

Here is the way is actually, if status variable is not null, code try to connect PDO database, otherwise connection is exists and will return true,NOT null.
Finally, in destruct function, connection has been closed by null value. When we want to connect database, we call the singleton like:
DB::connect();
If class has any other function, then like:
DB::connect()->functionName($param);

See you!

No comments:

Post a Comment

Thanks