Singleton Pattern |
//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:
See you!
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