Singleton method to handle database class and avoid "too many connections" errors
This commit is contained in:
parent
9c90c37dd8
commit
bbf107aa69
31
inc/MysqlConnector.php
Normal file
31
inc/MysqlConnector.php
Normal 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;
|
||||
}
|
||||
}
|
@ -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) {
|
||||
|
Loading…
Reference in New Issue
Block a user