Is this PDO wrapper structure dynamic? Can using self:: rather than $this cause problems?
class Database
extends PDO
{
/*@var mixed $stmt Used as a temporary variable to hold queries*/
private $stmt = Null;
/*@var $scopeSelectVar Used as a temporary variable to hold queries*/
private $scopeSelectVar = Null;
/*@Constructor __construct
*
* Database __construct ( mixed $db, [ string $serverHost = Null], [ string $dbName = Null],
* [ string $dbUser = Null], [ string $password = Null], [ bool $persistent = Null])
*
* @access-public
*/
public function __construct($db,
$serverHost = Null,
$dbName = Null, $dbUser = Null,
$password = Null, $persistent = true)
{
try
{
if(is_array($db))
{
/*
* parent::_construct allows easy instantiation and multiple database connections.
* @param mixed $db When array(), var holds all parameters required to connect.
* When string, var holds the type of DB to connect to. E.g. mysql
*
* @param string $serverHost the host of the DB connection
* @param string $dbName the name of the database
* @param string $dbUser the respective name of the user
* @param string $password the password of the user connecting
* @param bool $persistent if true, allows connection to persist through the app
*
*/
parent::__construct("{$db['dbType']}:host={$db['Host']};
dbname={$db['dbName']}",
$db['dbUser'],
$db['dbPassKey'],
array(
PDO::ATTR_PERSISTENT => $persistent,
));
}//if Var $db == array() then connect using array parameters
else
{
//else connect using all the other function parameters
parent::__construct("{$db}:host={$serverHost};
dbname={$dbName}", $dbUser, $password,
array(
PDO::ATTR_PERSISTENT => $persistent,
));
}
/*Uncomment if you have a proper log class*/
Log::write('../AppLogs/databaseConn.log', 'Connection
Established at:');
}
catch(PDOException $e)/*catching pdo exception and writing it to a file*/
{
/*Uncomment if you have a proper log class*/
Log::write('../AppLogs/databaseErrors.log',
'Error:'
.$e->getMessage());
}
}
/*
* @access private
*
* void defineParamType(string $val)
*
* */
private function defineParamType($val)
{
/*@param string $val the update or insert query data passed*/
/*@return const $param the param type constant returned from the function*/
switch($val):
case (is_int($val)):
$param = PDO::PARAM_INT;
break;
case (is_string($val)):
$param = PDO::PARAM_STR;
break;
case (is_bool($val)):
$param = PDO::PARAM_BOOL;
break;
case (is_Null($val)):
$param = PDO::PARAM_Null;
break;
default:
$param = Null;
endswitch;
return $param;
}
/*
* @access private
*
* void insertPrepare(array $bindData)
* */
private function insertPrepare($bindData)
{
/* @param array $bindData Data to be prepared for binding
* @return array $insertArray
* */
ksort($bindData);
$insertArray = array(
'fields' => implode("`,`", array_keys($bindData)),
'placeholders' => ':'.implode(',:',array_keys($bindData)),
);
return $insertArray;
}
/*
* @access private
*
* void updatePrepare(array $bindData)
* */
private function updatePrepare($bindData)
{
/*
* @param array $bindData Data to be prepared for binding
* @return string $placeHolders
* */
ksort($bindData);
$placeHolders = Null;
foreach($bindData as $key => $val)
{
$placeHolders .= "`$key`=:$key, ";
}
$placeHolders = rtrim($placeHolders, ', ');
return $placeHolders;
}
private function where($arguments = array(), $joinKeyword = 'AND')
{
ksort($arguments);
$whereClause = Null;
foreach($arguments as $key => $val)
{
if(is_int($val))
{
$whereClause .= "`$key` = $val {$joinKeyword} ";
}
else
{
$whereClause .= "`$key` = '$val' {$joinKeyword} ";
}
}
$whereClause = rtrim($whereClause, ' '.$joinKeyword.' ');
$whereClause = "WHERE {$whereClause}";
return $whereClause;
}
/*
* @access public
*
* void query(string $sql)
* */
public function query($sql)
{
/*
* @param string $sql the sql command to execute
* */
$this->scopeSelectVar = NULL;
$this->stmt = parent::query($sql);
}
/*
* @access public
*
* void insertRow(string $tableName, string $bindData)
*
* $array = array('field1'=>'field1Value')<-Notice the abscence of ":"
* $handler->insertRow('table', $array)
*
* */
public function insertRow($tableName, $bindData)
{
/*
* @param string $tableName Name of the table that is inserted into
* @param array $bindData array holding the set of column names
* respective data to be inserted
* */
try
{
$insertData = self::insertPrepare($bindData);
$this->stmt = parent::prepare("INSERT INTO
`{$tableName}` (`{$insertData['fields']}`)
VALUES({$insertData['placeholders']})");
foreach($bindData as $key => $val)
{
$param = self::defineParamType($val);
$this->stmt->bindValue(":$key", $val, $param);
}
$query = $this->stmt->execute();
}
catch(PDOException $e)
{
}
}
/*
* @access public
*
* void updateRow(string $tableName, array $bindData, string $target)
*
* Way of use: to update
* $array = array('field1'=>'field1Value')<-Notice the abscence of ":"
* $handler->updateRow('table', $array, '`field2`='Val'')
* */
public function updateRow($tableName, $bindData, $target,
$targetClause = 'AND')
{
/*
* @param string $tableName The name of the table you're updating
* @param array $bindData array of the values to be inserted.
* includes $_POST and $_GET
* @param string $target The exact update target. I.e.
* WHERE id='?'
* */
try
{
$updateData = self::updatePrepare($bindData);
if(isset($target))
{
$target = self::where($target, $targetClause);
}
$this->stmt = parent::prepare("UPDATE {$tableName}
SET {$updateData} {$target}");
foreach($bindData as $key => $val)
{
$param = self::defineParamType($val);
$this->stmt->bindValue(":$key", $val, $param);
}
$this->stmt->execute();
}
catch(PDOException $e)
{
}
}
/*
* @access public
*
* void deleteRow(string $tableName, string $target)
* */
public function deleteRow($tableName, $target)
{
/*
* @param string $tableName table to be deleted from
* @param string $target target of the delete query
* */
try
{
return parent::exec("DELETE FROM {$tableName} WHERE
{$target}");
}
catch(PDOException $e)
{
}
}
/*
* @access public
*
* void selectRow(string $fields, string $tableName, string $target)
* */
public function selectRow($fields, $tableName, array $target = NULL
, $targetClause = 'AND')
{
/*
* @param string $fields the fields of selection. E.g. '`field`,`field2`'...
* @param string $tableName The name of the target table
* */
if(isset($target))
{
$where = self::where($target, $targetClause);
}else
{
$where = Null;
}
self::query("SELECT {$fields} FROM {$tableName} {$where}");
}
/*
* @access public
*
* void fetch([string $singleReturn = false], [constant $fetchMode = PDO::FETCH_OBJ])
* */
public function fetch($singleReturn = false,
$fetchMode = PDO::FETCH_OBJ)
{
/*
* @param string $singleReturn the name of the "single" field to be fetching
* @param constant $fetchMode The fetch mode in which the data recieved will be stored
* @return mixed Null when conditions are not met, stdClass(object) or string when
* conditions are met.
* */
if(!isset($this->stmt)){return false;}
if($singleReturn == true)
{
if($this->scopeSelectVar == false)
{
$this->scopeSelectVar = $this->stmt->fetch($fetchMode);
if(isset($this->scopeSelectVar->$singleReturn))
{
return $this->scopeSelectVar->$singleReturn;
}else
return false;
}
}else
{
$this->scopeSelectVar = $this->stmt->fetch($fetchMode);
return (isset($this->scopeSelectVar)) ?
$this->scopeSelectVar: new StdClass;
}
}
/*
* @access public
*
* void fetchAll([constant $fetchMode = PDO::FETCH_ASSOC])
* */
public function fetchAll($fetchMode = PDO::FETCH_ASSOC)
{
/*
* @param constant $fetchMode Default is PDO::FETCH_ASSOC the mode of fetching data
* */
if(!isset($this->stmt)){return false;}
$fetchVar = $this->stmt->fetchAll($fetchMode);
return (!empty($fetchVar)) ? $fetchVar: new StdClass;
}
/*
* @TODO set a convenient method to quicly setup nested queries
* */
public function setSubQuery($target, $subQuery,
$mysqlSubQueryHandler)
{
//mysql nested query handler
}
/*
* @access public
*
* void rowCount()
* */
public function rowCount()
{
/*
* @return numeric $this->stmt->rowCount()
* */
if(isset($this->stmt))
{
return $this->stmt->rowCount();
}
}
/*
* @access public
*
* void lastId()
*
* */
public function lastId()
{
if(isset($this->stmt))
{
return parent::lastInsertId();
}
}
/*
* @access public
*
* void truncateTable(string $tableName)
* */
public function truncateTable($tableName)
{
/*
* @param string $tableName The name of table to be truncated
* Notice: truncation will reset the table and delete the data
* */
return self::query("TRUNCATE TABLE {$tableName}");
echo "Table {$tableName} Truncated on:".date("d-m-Y h:i:s")
."\n";
}
/*
* @access public
* void debugDumpParams()
*
* */
public function debugDumpParams()
{
return $this->stmt->debugDumpParams();
}
public function rankTable($tableName, $rankableColumn,
$orderByColumn, $ascDesc='DESC', $sqlVarName = 'rankNum')
{
self::query("SET @{$sqlVarName}:= 0");
self::query("UPDATE `{$tableName}` SET {$rankableColumn}
=@{$sqlVarName}:=@{$sqlVarName}+1
ORDER BY `{$orderByColumn}` {$ascDesc}");
}
public function
public function __destruct()
{
}
}
I know I probably shouldn't be extending on PDO, but the entire architecture will be redesigned. I just need to make sure the other functions are somewhat nicely coded.
This is my first heavy OOP code design. Please criticise.