The BaseDbClass
is an abstract class that offers three major pieces of functionality:
tryPdoExcept()
, which takes care of catching and logging
PDOException's that happen while executing queries against the PDO
dependency
The BaseDbClass::__initialize()
method can be overridden by child classes to execute code as
though it were being done in a constructor, but will only be called if the BaseDbClass
constructor has received appropriate PDO
and Logger
dependencies:
using Stoic\Pdo\BaseDbClass;
class MyDbClass extends BaseDbClass {
public $isInitialized = false;
protected function __initialize() : void {
// If we are here, we have $this->db and $this->log
$this->isInitialized = true;
$this->log->info("MyDbClass was initialized successfully");
return;
}
}
Whether using the normal PDO
OR PdoHelper
classes, a common set of code is the
following:
public function getAllSomethings() {
// some stuff to prepare a query....
try {
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':var', $var, \PDO::PARAM_STR);
$stmt->execute();
// gather results, etc
} catch (\PDOException $ex) {
$this->log->error("Issue executing query: {ERROR}", ['ERROR' => $ex]);
}
return $ret;
}
Since it's very likely that this code will be used periodically within a codebase, the
BaseDbClass
abstract provides a utility method, tryPdoExcept()
. This allows us to
refactor the above into this:
public function getAllSomethings() {
// some stuff to prepare a query
$this->tryPdoExcept(function () use ($sql, &$ret) {
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':var', $var, \PDO::PARAM_STR);
$stmt->execute();
// gather results, etc
}, "Issue executing query");
return $ret;
}
Continue to read about the BaseDbModel within the PDO component, or visit the Table of Contents.