Removed global variables from the Database class constructor and updated tests for the Database class

This commit is contained in:
Dmitriy Simushev 2012-09-07 13:27:40 +00:00
parent 4db2ce5175
commit 0861fd73d2
3 changed files with 117 additions and 83 deletions

View File

@ -22,16 +22,19 @@ class DatabaseTest extends PHPUnit_Framework_TestCase {
$this->object = Database::getInstance(); $this->object = Database::getInstance();
} }
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
$this->object->__destruct();
}
public static function setUpBeforeClass() { public static function setUpBeforeClass() {
global $mysqlhost, $mysqllogin, $mysqlpass, $mysqldb; global $mysqlhost, $mysqllogin, $mysqlpass, $mysqldb, $dbencoding,
$mysqlprefix, $use_persistent_connection, $force_charset_in_connection;
Database::initialize(
$mysqlhost,
$mysqllogin,
$mysqlpass,
$use_persistent_connection,
$mysqldb,
$mysqlprefix,
$force_charset_in_connection,
$dbencoding
);
$dbh = new PDO( $dbh = new PDO(
"mysql:host={$mysqlhost};dbname={$mysqldb}", "mysql:host={$mysqlhost};dbname={$mysqldb}",
$mysqllogin, $mysqllogin,
@ -53,6 +56,7 @@ class DatabaseTest extends PHPUnit_Framework_TestCase {
); );
$dbh->exec("DROP TABLE phpunit_test_only"); $dbh->exec("DROP TABLE phpunit_test_only");
$dbh = NULL; $dbh = NULL;
Database::destroy();
} }
public function testGetInstance() { public function testGetInstance() {
@ -61,6 +65,22 @@ class DatabaseTest extends PHPUnit_Framework_TestCase {
$anotherDatabaseInstance = NULL; $anotherDatabaseInstance = NULL;
} }
public function testErrorInfo() {
$this->object->throwExeptions(true);
$this->assertFalse($this->object->errorInfo());
try{
$this->object->query("SOME_FAKE_QUERY");
$this->fail('Exception must be thrown!');
} catch(Exception $e) {
$errorInfo = $this->object->errorInfo();
$this->assertEquals('42000', $errorInfo[0]);
$this->assertEquals(1064, $errorInfo[1]);
}
$this->object->query("SELECT 'test_value'");
$errorInfo = $this->object->errorInfo();
$this->assertEquals('00000', $errorInfo[0]);
}
public function testQuery() { public function testQuery() {
global $mysqlprefix; global $mysqlprefix;
@ -141,22 +161,6 @@ class DatabaseTest extends PHPUnit_Framework_TestCase {
$this->assertEquals($mysqlprefix.'test', $result['field_name']); $this->assertEquals($mysqlprefix.'test', $result['field_name']);
} }
public function testErrorInfo() {
$this->object->throwExeptions(true);
$this->assertFalse($this->object->errorInfo());
try{
$this->object->query("SOME_FAKE_QUERY");
$this->fail('Exception must be thrown!');
} catch(Exception $e) {
$errorInfo = $this->object->errorInfo();
$this->assertEquals('42000', $errorInfo[0]);
$this->assertEquals(1064, $errorInfo[1]);
}
$this->object->query("SELECT 'test_value'");
$errorInfo = $this->object->errorInfo();
$this->assertEquals('00000', $errorInfo[0]);
}
public function testInsertedId() { public function testInsertedId() {
$this->object->query("INSERT INTO phpunit_test_only (id) VALUES (NULL)"); $this->object->query("INSERT INTO phpunit_test_only (id) VALUES (NULL)");
$actual_id = $this->object->insertedId(); $actual_id = $this->object->insertedId();

View File

@ -111,47 +111,49 @@ Class Database{
protected $throwExceptions = false; protected $throwExceptions = false;
/** /**
* Get instance of Database class. If no instance exists, creates new instance. * Get instance of Database class.
*
* If no instance exists, creates new instance.
* Use Database::initialize() before try to get an instance. If database was not initilize coorectly triggers an
* error with E_USER_ERROR level.
* *
* @return Database * @return Database
* @see Database::initialize()
*/ */
public static function getInstance(){ public static function getInstance(){
if (is_null(self::$instance)) { if (is_null(self::$instance)) {
self::$instance = new Database(); trigger_error('Database was not initialized correctly', E_USER_ERROR);
} }
return self::$instance; return self::$instance;
} }
/** /**
* Forbid clone objects * Destroy internal database object
*/ */
private final function __clone() {} public static function destroy(){
if (! is_null(self::$instance)) {
self::$instance->__destruct();
self::$instance = NULL;
}
}
/** /**
* Database class constructor. Set internal database and connection * Initialize database.
* properties. Create PDO object and store it in the Database object.
* *
* @global string $mysqlhost Contains mysql host. defined in * Set internal database and connectionproperties. Create Database object. Create PDO object and store it in the
* libs/config.php * Database object.
* @global string $mysqllogin Contains mysql login. Defined in *
* libs/config.php * @param string $host Database host.
* @global string $mysqlpass Contains mysql password. Defined in * @param string $user Database user name.
* libs/config.php * @param string $pass Database for user with $name password.
* @global string $mysqldb Contains mysql database name. Defined in * @param boolean $use_pconn Control use persistent connection to the database or not.
* libs/config.php * @param string $db Database name.
* @global string $dbencoding Contains connection encoding. Defined in * @param string $prefix Database tables prefix
* libs/config.php * @param boolean $force_charset Control force charset in conection or not.
* @global string $mysqlprefix Contains mysql tables prefix. Defined in * @param string $encoding Contains connection encoding. Using only if $force_charset = true.
* libs/config.php
* @global boolean $force_charset_in_connection Control force charset in
* conection or not. Defined in libs/config.php
* @global boolean $use_persistent_connection Control use persistent
* connection to the database or not. Defined in libs/config.php
*/ */
protected function __construct(){ public static function initialize($host, $user, $pass, $use_pconn, $db, $prefix, $force_charset = false, $encoding = 'utf8') {
global $mysqlhost, $mysqllogin, $mysqlpass, $mysqldb, $dbencoding, // Check PDO
$mysqlprefix, $force_charset_in_connection, $use_persistent_connection;
try{
if (! extension_loaded('PDO')) { if (! extension_loaded('PDO')) {
throw new Exception('PDO extension is not loaded'); throw new Exception('PDO extension is not loaded');
} }
@ -160,32 +162,48 @@ Class Database{
throw new Exception('pdo_mysql extension is not loaded'); throw new Exception('pdo_mysql extension is not loaded');
} }
// Check if initialization
if (! is_null(self::$instance)) {
throw new Exception('Database already initialized');
}
// Create database instance
$instance = new Database();
// Set database and connection properties // Set database and connection properties
$this->dbHost = $mysqlhost; $instance->dbHost = $host;
$this->dbLogin = $mysqllogin; $instance->dbLogin = $user;
$this->dbPass = $mysqlpass; $instance->dbPass = $pass;
$this->dbName = $mysqldb; $instance->dbName = $db;
$this->dbEncoding = $dbencoding; $instance->dbEncoding = $encoding;
$this->tablesPrefix = $mysqlprefix; $instance->tablesPrefix = $prefix;
$this->forceCharsetInConnection = $force_charset_in_connection; $instance->forceCharsetInConnection = $force_charset;
$this->usePersistentConnection = $use_persistent_connection; $instance->usePersistentConnection = $use_pconn;
// Create PDO object // Create PDO object
$this->dbh = new PDO( $instance->dbh = new PDO(
"mysql:host={$this->dbHost};dbname={$this->dbName}", "mysql:host={$instance->dbHost};dbname={$instance->dbName}",
$this->dbLogin, $instance->dbLogin,
$this->dbPass $instance->dbPass
); );
if ($this->forceCharsetInConnection) { if ($instance->forceCharsetInConnection) {
$this->dbh->exec("SET NAMES ".$this->dbh->quote($this->dbEncoding)); $instance->dbh->exec("SET NAMES ".$instance->dbh->quote($instance->dbEncoding));
} }
} catch(Exception $e) { // Store instance
$this->handleError($e); self::$instance = $instance;
}
} }
/**
* Forbid clone objects
*/
private final function __clone() {}
/**
* Forbid external object creation
*/
protected function __construct() {}
/** /**
* Handles errors * Handles errors
* @param Exception $e * @param Exception $e

View File

@ -26,6 +26,18 @@ require_once(dirname(__FILE__) . '/classes/settings.php');
$version = '1.6.5'; $version = '1.6.5';
$jsver = "165"; $jsver = "165";
// Initialize the database
Database::initialize(
$mysqlhost,
$mysqllogin,
$mysqlpass,
$use_persistent_connection,
$mysqldb,
$mysqlprefix,
$force_charset_in_connection,
$dbencoding
);
function myiconv($in_enc, $out_enc, $string) function myiconv($in_enc, $out_enc, $string)
{ {
global $_utf8win1251, $_win1251utf8; global $_utf8win1251, $_win1251utf8;