Singleton method to handle database class and avoid "too many connections" errors

This commit is contained in:
Phyks 2013-11-24 22:16:32 +01:00
parent 9c90c37dd8
commit bbf107aa69
2 changed files with 35 additions and 49 deletions

31
inc/MysqlConnector.php Normal file
View File

@ -0,0 +1,31 @@
<?php
class MysqlConnector {
private $connection = null;
private static $instance = null;
private function __construct() {
$this->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;
}
}

View File

@ -1,68 +1,23 @@
<?php
require_once('data/config.php');
require_once('inc/MysqlConnector.php');
class Storage {
private $connection = null;
private $mysql_instance = null;
public function __construct() {
$this->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) {