Last updated: August 12th, 2023

The BaseDbModel class is a simplistic scaffolding system that was built to simplify/speed-up the creation of CRUD (Create - Read - Update - Delete) data models without extensive overhead or having to use something other than the SQL we all know and love/hate.

The system provides the following features:

  • Simple column/property association for CRUD functionality
  • Ability to override CRUD guards and impose custom validation
  • Automatic translation of database values to PHP values
  • Query string generation

CRUD Automation

In order to take advantage of the CRUD system within BaseDbModel, simply tell your model during initialization (inside of the __setupModel() method) what the class properties relate to and in what table:

use Stoic\Pdo\BaseDbModel;
use Stoic\Pdo\BaseDbTypes;

class UserModel extends BaseDbModel {
	 * Unique identifier for user.
	 * @var integer
	public $id;
	 * User's primary email address.
	 * @var string
	public $email;
	 * The date and time the user joined the site.
	 * @var DateTimeInterface
	public $dateJoined;

	protected function __setupModel() {
		$this->setColumn('id', 'ID', BaseDbTypes::INTEGER, true, false, false, false, true);
		$this->setColumn('email', 'Email', BaseDbTypes::STRING, false, true, true);
		$this->setColumn('dateJoined', 'DateJoined', BaseDbTypes::DATETIME, false, true, false);


That's it! Now any instance of the UserModel class comes complete with (among many other things) a full assortment of CRUD methods.

If one of your CRUD methods, let's say 'create', needs a bit more validation before it attempts to do its thing, adding that validation is very easy. All you need to is add an override for the __canCreate() method:

protected function __canCreate() {
	if ($this->id > 0 || empty($this->email)) {
		return false;

	$this->dateJoined = new DateTime('now', new DateTimeZone('UTC'));

	return true;

Similar methods exist for read, update, and delete.

Query Generation

Another utility method is the BaseDbModel::generateClassQuery() method. This allows devs to get dynamically generated SQL strings for their model classes, useful if you find yourself using the models for things like repository methods. This also decreases the amount of SQL you'll have to change by hand when you update your schema.

use Stoic\Pdo\BaseDbQueryTypes;

// We'll assume we have a database connection ready to use
$user = new UserModel($db);
$sql = $user->generateClassQuery(BaseDbQueryTypes::SELECT);

// $sql contains the following string:
//    "SELECT ID, Email, DateJoined FROM User WHERE ID = :id"

$sql = $user->generateClassQuery(BaseDbQueryTypes::SELECT, false);

// $sql will now contain the following string:
//    "SELECT ID, Email, DateJoined FROM User"

Next Up

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