BaseDbClass

Last updated: August 12th, 2023
Release:

The BaseDbClass is an abstract class that offers three major pieces of functionality:

  1. Enforces the requirement that any derived classes must have PDO and Logger objects injected into them at instantiation
  2. An optional initialization method devs can override to perform their init steps knowing they have the PDO & Logger dependencies
  3. A utility method, tryPdoExcept(), which takes care of catching and logging PDOException's that happen while executing queries against the PDO dependency

Initialization

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;
	}
}

tryPdoExcept

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;
}

Next Up

Continue to read about the BaseDbModel within the PDO component, or visit the Table of Contents.