stave.dev

Models & Database

One PDO connection, a thin row gateway for fixed tables, and model classes that load by namespace. No ORM, no query builder.

What core provides

Class File Is
Zero\Core\Database core/Database.php The shared PDO connection, built from app/config/database.ini, for mysql, pgsql or sqlite
Zero\Core\Model core/Model.php An abstract typed row gateway over one table. Optional: a model can also be a plain class.

The Entity Framework is a third, optional way to store data: an EAV layer that ships in core/entity/ and needs no table per type. It is a different tool from Zero\Core\Model, which is for a real table with real columns.

This site has no database

stave.dev is static documentation. The listings on this page are examples for your application, not code this site runs.

Model Directory

Models live in a model/ directory inside your module, in the namespace Zero\Module\{Module}\Model. They are loaded by name — no require or include needed.

modules/ Article/ Article.php ← Controller model/ ArticleModel.php ← Auto-loaded CategoryModel.php ← Auto-loaded view/
File Class
modules/Article/model/ArticleModel.php Zero\Module\Article\Model\ArticleModel
modules/UserProfile/model/Avatar.php Zero\Module\UserProfile\Model\Avatar
modules/Shop/submodule/Catalog/model/Item.php Zero\Module\Shop\Catalog\Model\Item
How Auto-Loading Works

Application::classFile() maps the namespace to the path: the Model segment is the module's model/ folder and the class name is the filename. The same rule serves a request, a cron script and a test. Class Loading has the whole rule.

A model is private to its module

Another module does not call your model/ classes. What other modules need goes in the module's lib/ folder (Zero\Module\{Module}\Lib), so the module's own rules apply wherever its data changes.

Database Connection

Database::getConnection() returns the one shared PDO. It is created on the first call, from the constants app/config/database.ini defines, and every later call returns the same instance.

use Zero\Core\Database;

// Get the shared PDO connection (lazy-loaded on first call)
$db = Database::getConnection();

// The connection uses these PDO options by default:
// - ERRMODE_EXCEPTION — errors throw exceptions
// - FETCH_ASSOC — fetches return associative arrays
// - EMULATE_PREPARES = false — real prepared statements

Two things can stop it, and both throw a plain \Exception:

Case Message What happens
No database configured: Database::isConfigured() is falseDatabase is not configured: set DB_DRIVER, NAME and USER in app/config/database.iniNo connection is attempted and nothing is logged.
Configured, but the connection cannot be openedDatabase connection failedThe PDO message is logged at CRITICAL and kept out of the exception, so credentials never reach the page.

Database::isConfigured(): bool is public. It is true when DB_DRIVER and NAME are not blank and, unless the driver is sqlite, USER is not blank either. Call it before a query a page can do without:

$rows = Database::isConfigured()
    ? Database::getConnection()->query('SELECT id, title FROM articles')->fetchAll()
    : [];

database.ini

HOST=localhost
NAME=myapp
USER=dbuser
PASS=dbpass

; PDO driver: mysql | pgsql | sqlite. Required: there is no default.
DB_DRIVER=mysql
; Blank uses the driver's own default port (3306 mysql, 5432 pgsql).
DB_PORT=
; Client encoding. Blank means utf8mb4 on mysql and the server default on pgsql.
DB_CHARSET=
Key Required Meaning
HOSTNoServer hostname; localhost when the key is absent. Ignored by sqlite.
NAMEYesDatabase name. For sqlite, the file path or :memory:.
USERYes, except sqliteThe account to connect as.
PASSNoIts password. May be blank.
DB_DRIVERYesmysql, pgsql or sqlite. There is no default: with the key absent or blank nothing connects.
DB_PORTNoAbsent or blank leaves the port to the driver.
DB_CHARSETNoOn mysql it goes into the DSN and defaults to utf8mb4. On pgsql a value becomes options='--client_encoding=...', so use a Postgres name such as UTF8.

With a required key blank or absent, getConnection() opens nothing. A site with no database leaves NAME and USER blank (Running Without a Database).

The template is core/skeleton/config-templates/database.ini. Any other driver name falls through to a generic driver:host=...;dbname=... DSN (Database::buildDsn()).

A second database

Database::connect() opens a standalone connection with the same PDO options and leaves the shared one alone. The caller owns the handle. It takes its settings from the array, not from database.ini, and an array with no driver key means mysql.

$reports = Database::connect([
    'driver'  => 'pgsql',
    'host'    => 'reports.internal',
    'port'    => 5432,
    'name'    => 'warehouse',
    'user'    => 'reader',
    'pass'    => 'secret',
    'charset' => 'UTF8',
]);

$cache = Database::connect(['driver' => 'sqlite', 'name' => ':memory:']);

Database::init() takes the same array, or an existing PDO, and makes it the shared connection. It returns false and changes nothing when a shared connection already exists, so call it before anything asks for one.

Zero\Core\Model — a typed row gateway

A model can be a plain class holding a PDO, as shown below, and for hand-written joins that is still the right shape. For the common case — one table, fixed columns — core ships Zero\Core\Model (core/Model.php), an abstract base that removes the boilerplate.

It is deliberately not an ORM. There is no relationship mapping, no lazy loading and no query builder; it is a row gateway with a writable-column whitelist. Declare the table, the primary key and the columns, and you get typed reads and writes:

<?php
namespace Zero\Module\Article\Model;

class Article extends \Zero\Core\Model {

    protected static string $table   = 'articles';
    protected static string $pk      = 'id';

    /* Writable columns. Anything outside this list is never written and never
       reaches the SQL — the DDL owns id/created_at/updated_at. */
    protected static array $columns  = ['title', 'body', 'status', 'author_id'];
}
$article = Article::find(42);              // ?static — null when absent
$article = Article::findBy('title', 'Hello'); // ?static — always ONE row
$drafts  = Article::allBy('status', 'draft'); // array of static

$new = Article::create(['title' => 'New', 'body' => '...']);

$article->title = 'Corrected';            // staged, not written
$article->save();                          // writes only the staged columns
$article->delete();
save() writes only what changed

Columns are staged as you set them, so an instance built from partial data cannot clobber the rest of the row with stale values.

Member Behaviour
static find(int|string $id): ?staticOne row by primary key.
static findBy(string $column, $value): ?staticAt most one row (LIMIT 1).
static allBy(string $column, $value): arrayEvery matching row, as instances.
static create(array $data): staticInserts and returns the instance with its primary key set.
save(): voidInsert when new, update the staged columns when loaded, nothing when nothing changed.
delete(): voidDeletes the row. Nothing for an instance that was never saved.
toArray(): arrayThe row, column to value.
$model->columnReads return null for a column the row lacks. A write to a column outside $columns is ignored, not an error.
static isDuplicateKey(\PDOException $e): boolTrue for a UNIQUE violation specifically (mysql 1062, pgsql 23505), so a duplicate can become a clean message.

findBy() always returns a single ?static — use allBy() when you want many. That is a deliberate incompatibility with the Entity Framework's where(), which returns null, one entity, or an array depending on how many rows matched.

findBy() and allBy() accept only the primary key or a name in $columns; any other column name throws InvalidArgumentException. That whitelist is what makes it safe to put the column name into the SQL.

The generated SQL is plain ANSI — no backtick quoting — so a model does not pin the application to MySQL. On pgsql the new id is read from the sequence {table}_{pk}_seq. The tradeoff of unquoted identifiers is that a column named after a reserved word cannot be used.

Every query goes through Database::getConnection(), the shared connection. A model on a second database is a plain class holding the handle Database::connect() returned.

try {
    Article::create(['title' => $title, 'body' => $body]);
} catch (\PDOException $e) {
    if (!Article::isDuplicateKey($e)) {
        throw $e;
    }
    throw new HTTPError(400, 'An article with that title already exists');
}

A plain PDO model

A model does not have to extend anything. A plain class that receives a PDO connection in its constructor is the right shape for joins, reports and anything else you want to write by hand:

<?php
namespace Zero\Module\Article\Model;

class ArticleModel {

    private \PDO $db;

    public function __construct(\PDO $db) {
        $this->db = $db;
    }

    /**
     * Find a single article by ID
     */
    public function find(int $id): ?array {
        $stmt = $this->db->prepare("
            SELECT * FROM articles WHERE id = :id
        ");
        $stmt->execute(['id' => $id]);
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $result ?: null;
    }

    /**
     * Get all articles, newest first
     */
    public function getAll(int $limit = 50, int $offset = 0): array {
        $stmt = $this->db->prepare("
            SELECT * FROM articles
            ORDER BY created_at DESC
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
        $stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Create a new article
     */
    public function create(array $data): int {
        $stmt = $this->db->prepare("
            INSERT INTO articles (title, content, user_id)
            VALUES (:title, :content, :user_id)
        ");
        $stmt->execute([
            'title'   => $data['title'],
            'content' => $data['content'],
            'user_id' => $data['user_id'],
        ]);
        return (int) $this->db->lastInsertId();
    }

    /**
     * Update an article
     */
    public function update(int $id, array $data): bool {
        $stmt = $this->db->prepare("
            UPDATE articles
            SET title = :title, content = :content
            WHERE id = :id
        ");
        return $stmt->execute([
            'id'      => $id,
            'title'   => $data['title'],
            'content' => $data['content'],
        ]);
    }

    /**
     * Delete an article
     */
    public function delete(int $id): bool {
        $stmt = $this->db->prepare("DELETE FROM articles WHERE id = :id");
        return $stmt->execute(['id' => $id]);
    }
}

Using Models in Controllers

Instantiate your model in the controller's constructor, passing the database connection:

<?php
namespace Zero\Module;

use Zero\Core\Database;
use Zero\Core\Exception\HTTPError;
use Zero\Module\Article\Model\ArticleModel;

class Article extends \Zero\Core\Module {

    private ArticleModel $model;

    public function __construct() {
        parent::__construct();
        $db = Database::getConnection();
        $this->model = new ArticleModel($db);
    }

    public function index() {
        $this->data = ['articles' => $this->model->getAll()];
        $this->respond($this->viewPath . 'index.php');
    }

    public function show($id) {
        $article = $this->model->find($id);
        if (!$article) {
            throw new HTTPError(404, 'Article not found');
        }
        $this->data = ['article' => $article];
        $this->respond($this->viewPath . 'show.php');
    }
}
Always Call parent::__construct()

If you override the constructor, you must call parent::__construct() first. The parent constructor resolves the module's paths and links its assets. Without it, $this->viewPath and $this->modelPath are not set. See Modules.

Using Models in Views

Since view files have access to $this (the module instance), they can use any data the controller set:

<article>
    <h1><?= htmlspecialchars($this->data['article']['title']) ?></h1>
    <div class="content">
        <?= $this->data['article']['content'] ?>
    </div>
</article>

Direct Database Access

For simple one-off queries, you can use Database directly in a controller without creating a model class:

use Zero\Core\Database;

public function stats() {
    $db = Database::getConnection();

    $stmt = $db->query("SELECT COUNT(*) as total FROM articles");
    $count = $stmt->fetch(\PDO::FETCH_ASSOC);

    $this->data = ['total' => $count['total']];
    $this->respond($this->viewPath . 'stats.php');
}
When to Use a Model

If you have more than a couple of queries, or if the same query is needed in multiple endpoints, put it in a model. Models keep your controller focused on request handling and your SQL organized in one place.

Prepared Statements

With EMULATE_PREPARES set to false by default, all queries use real prepared statements. Always use parameterized queries to prevent SQL injection:

// Named parameters
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);

// Positional parameters
$stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND active = ?");
$stmt->execute([$id, 1]);

// Use bindValue for LIMIT/OFFSET (requires explicit type)
$stmt = $db->prepare("SELECT * FROM articles LIMIT :limit OFFSET :offset");
$stmt->bindValue('limit', 20, \PDO::PARAM_INT);
$stmt->bindValue('offset', 0, \PDO::PARAM_INT);
$stmt->execute();
Never Interpolate User Input

Always use prepared statements with bound parameters. Never concatenate $_GET, $_POST, or any user input directly into SQL strings. The PDO connection is configured with real prepared statements enabled by default.

Query tracking

core/Database.php can time and record every statement a request runs. It is off until something calls Database::enableQueryTracking(); core itself never does. Once on, the shared connection and any connection opened with connect() use a PDOStatement subclass, TrackedStatement, so statements prepared directly on the PDO are recorded too.

Database::enableQueryTracking();

// ... the request runs ...

foreach (Database::getQueries() as $q) {
    // $q['sql']     the statement text
    // $q['params']  bound values, bindValue()/bindParam() and execute() merged
    // $q['ms']      execution time in milliseconds
    // $q['rows']    rowCount()
}

It is meant for a development toolbar plugin, which switches it on in afterConstants() and reads the list in afterRun(). Statements run with PDO::query() or PDO::exec() do not pass through execute() and are not recorded.

What is not loaded

core/deprecated/SQLAdapter.php is an old active-record class kept in the repository. Nothing loads it, and it extends an Adapter class that does not exist in core (core/README.md). Do not build on it; use Zero\Core\Model, a plain PDO class, or the Entity Framework.