I've built a Connection class that uses a PDO connection, but it looks messy and I'm sure there are ways of improving it. Currently I only want 1 instance of the connection (singleton).
<?php
namespace AQEConnect {
interface ICredentials {
function Username();
function Password();
}
interface IDbProvider {
function Options();
}
class DatabaseException extends \Exception {
}
abstract class SqlConnection implements IDbProvider {
protected $_connection_type;
private $_connection = null;
private $_connection_string;
private $_credentials;
public function __construct($connection_string, ICredentials $credentials) {
$this->_connection_string = $connection_string;
$this->_credentials = $credentials;
}
public function get() {
$this->_connect();
return $this->_connection;
}
private function _connect() {
if ($this->_connection === null)
try {
$this->_verifyIsSet($this->_connection_type, $this->_connection_string,
$this->_credentials->Username(), $this->_credentials->Password(), $this->Options());
$this->_connection = new \PDO($this->_connection_type . $this->_connection_string,
$this->_credentials->Username(), $this->_credentials->Password(), $this->Options());
} catch (\PDOException $exception) {
$this->_connection = null;
throw new DatabaseException('Database connection exception', $exception);
}
}
protected function _close() {
$this->_connection = null;
}
/**
* @return bool Whether the class currently has a connection.
*/
public function hasConnection() {
return $this->_connection !== null && $this->_connection instanceof \PDO;
}
private function _verifyIsSet() {
foreach (func_get_args() as $arg)
if (empty($arg))
throw new DatabaseException('Required database variable not set.');
}
public function __destruct() {
$this->_close();
}
/**
* @return string Current Connection class details.
*/
public function __toString() {
return $this->hasConnection() ? 'Connected to: ' . DBNAME . '.' : 'No Connection.';
}
}
class MysqlConnection extends SqlConnection {
public function __construct($connection_string, ICredentials $credentials) {
$this->_connection_type = 'mysql:';
parent::__construct($connection_string, $credentials);
}
public function Options() {
return array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_SILENT);
}
}
}
Its called like this:
class DbCredentials implements ICredentials {
public function UserId() {
return 'test';
}
public function Password() {
return '12345';
}
}
class foo
{
private static $_connection = null;
private static function _connect() {
if (self::$_connection === null)
self::$_connection = new MysqlConnection('host=localhost;port=1111;dbname=test', new DbCredentials());
}
}
EDIT: Updated my connection class to an updated version (Thanks to Peter Kiss' answer), I'm still looking for any help from anyone who can suggest any modifications!