From bbf107aa69ed0711ca9f644f3d30c640fa53792d Mon Sep 17 00:00:00 2001 From: Phyks Date: Sun, 24 Nov 2013 22:16:32 +0100 Subject: [PATCH] Singleton method to handle database class and avoid "too many connections" errors --- inc/MysqlConnector.php | 31 ++++++++++++++++++++++++ inc/Storage.class.php | 53 ++++-------------------------------------- 2 files changed, 35 insertions(+), 49 deletions(-) create mode 100644 inc/MysqlConnector.php diff --git a/inc/MysqlConnector.php b/inc/MysqlConnector.php new file mode 100644 index 0000000..b250c45 --- /dev/null +++ b/inc/MysqlConnector.php @@ -0,0 +1,31 @@ +connect(); + } + + public function connect() { + $this->connection = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_LOGIN, MYSQL_PASSWORD); + $this->connection->query('SET NAMES utf8'); + } + + public function disconnect() { + $this->connection = null; + } + + public function getConnection() { + return $this->connection; + } + + public static function getInstance() { + + if (self::$instance === null) { + self::$instance = new self(); + } + return self::$instance; + } +} diff --git a/inc/Storage.class.php b/inc/Storage.class.php index 6e68714..fbd6c9d 100644 --- a/inc/Storage.class.php +++ b/inc/Storage.class.php @@ -1,68 +1,23 @@ connect(); + $this->mysql_instance = MysqlConnector::getInstance(); + $this->connection = $this->mysql_instance->getConnection(); } public function __destruct() { - $this->disconnect(); - } - - // Connection functions - // ==================== - public function connect() { - $this->connection = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_LOGIN, MYSQL_PASSWORD); - $this->connection->query('SET NAMES utf8'); - } - - public function disconnect() { - $this->connection = null; - } - - // Getters - // ======= - public function getHost() { - return $this->host; - } - - public function getLogin() { - return $this->login; - } - - public function getPassword() { - return $this->password; - } - - public function getDb() { - return $this->db; } public function getConnection() { return $this->connection; } - // Setters - // ======= - public function setHost($host) { - $this->host = host; - } - - public function setLogin($login) { - $this->login = $login; - } - - public function setPassword($password) { - $this->password = $password; - } - - public function setDb($db) { - $this->db = $db; - } - // Translates types in class to SQL types // ====================================== public function typeToSQL($type) {