I have written a PDO wrapper and a class file like a model. So far, it's looking so good! I am just confuse where I should put Try...Catch block - Would it be better to place in PDO wrapper (pdoDatabase.php), mobile.php (model) or test.php?
See the code below,
pdoDatabase.php
class pdoDatabase {
public $db;
private $sth;
private static $instance;
private $error;
private function __construct() {
$dsn = "mysql:dbname=" . config::read("db.database") . ";host=localhost";
$username = config::read("db.username");
$password = config::read("db.password");
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new static();
}
return self::$instance;
}
public function fetchData($sql, $params = array(), $fetchMode = 'all') {
// Should try...catch block be here?
try {
$this->sth = $this->db->prepare($sql);
if (count($params) > 0)
$this->setBind($params);
$this->sth->execute();
$fetch = ($fetchMode == 'single') ? "fetch" : "fetchAll";
return $this->sth->$fetch();
} catch (PDOException $e) {
$this->error = array(
'status' => 'error',
'message' => $e->getMessage()
);
return false;
}
}
public function setBind($params) {
if (is_object($this->sth)) {
foreach ($params as $key => $value) {
$this->sth->bindValue(":$key", $value);
}
}
}
public function error() {
return $this->error;
}
public function beginTransaction() { }
public function commit() { }
public function rollBack() { }
mobile.php
class Mobile {
public $db;
public function __construct() {
$this->db = pdoDatabase::getInstance();
}
public function findPhoneAffiliate($phoneId = null, $affiliateId = null, $affiliatePhoneId = null) {
// or should try...catch block be here?
$bindAr = array();
if ($phoneId !== null)
$whereAr[] = "phone_id = " . $phoneId;
if ($affiliateId !== null)
$whereAr[] = 'affiliate_id = ' . $affiliateId;
if ($affiliatePhoneId !== null) {
$whereAr[] = 'affiliate_phone_id = :affiliate_phone_id';
$bindAr['affiliate_phone_id'] = $affiliatePhoneId;
}
$where = count($whereAr) > 0 ? 'WHERE ' . implode(' AND ', $whereAr) : '';
$sql = "SELECT * FROM phone_affiliate $where";
return $this->db->fetchData($sql, $bindAr, 'single');
}
}
test.php
$mobileResult = $mobile->findPhoneAffiliate(null, 'f', "ASEF33");
if ($mobileResult) {
// Data Found!
print_r($mobileResult);
} else {
if ($mobile->db->error()) {
print_r($mobile->db->error());
exit();
}
if ($mobile->db->rowCount() == 0)
echo "Data Not Found";
}
As you can see it will need to check if there any error or no data found in the else statement. Is this how it should be done or what can be improved so it can redude the code from test.php sample ?