stave.dev

Examples

An annotated tour: the simplest hand-written class, core's own Event log, and a type generated with GenericEntity::define() from definition to query.

These are listings for the reader. This site has no database and runs none of them.

Example 1 — Note: The Minimum Viable Entity

The simplest hand-written entity declares a unique attribute and nothing else. The schema is defined by whoever calls the constructor first.

<?php
namespace Zero\Entity;

class Note extends Entity {
    public $uniq = ['title'];
}

The file goes in the site's entity/ folder and autoloads. The first new Note([...]) call sets the schema:

new \Zero\Entity\Note([
    'title'      => 'First Note',
    'body'       => 'Hello, world.',
    'created_at' => date('Y-m-d H:i:s'),
]);
// schema is now: title, body, created_at

From now on, note_view has the columns (id, title, body, created_at), and storing a second note with the same title throws Duplicate entry found for title with id 1.

Example 2 — Event: Core's Event Log

Zero\Entity\Event (core/entity/Event.php) is the one entity type core uses itself. core/sql/core.sql seeds its type, its four schema rows (datetime, event, detail, ip) and event_view. Its constructor fills in what should not be left to the caller: datetime and ip when they are absent, the latter from \Zero\Core\Request::clientIp(). It also cuts a detail longer than 255 characters to fit and logs the cut. The full listing is on Creating Types.

Callers stay small:

new \Zero\Entity\Event(['event' => 'login', 'detail' => 'ok']);
new \Zero\Entity\Event(['event' => 'password_reset', 'detail' => $email]);

Core writes events from the #[AuditLog] attribute (core/attribute/AuditLog.php, see Attributes), from core/lib/Mail/Mail.php and from the Auth module. Read them from the view:

$db = \Zero\Core\Database::getConnection();
$stmt = $db->prepare(
    "SELECT id, datetime, event, detail, ip FROM event_view WHERE event = ? ORDER BY datetime DESC, id DESC LIMIT 50"
);
$stmt->execute(['login']);
$rows = $stmt->fetchAll();

The Admin module's audit log at /admin/audit is the same read with filters (core/modules/Admin/model/EventLog.php).

Example 3 — Product: Programmatic Definition

A hypothetical Product type created with GenericEntity::define(). This is the path when the type is a fixed list of attributes and you'd rather not write the class file.

\Zero\Entity\GenericEntity::define('product', [
    'attributes' => [
        'name',
        'price',
        'sku',
        'status',
        'stock',
        'created_at',
    ],
    'defaults' => [
        'status'     => 'active',
        'stock'      => '0',
        'created_at' => 'date:Y-m-d H:i:s',
    ],
    'uniq' => ['sku'],
]);

Run it once, inside a request so that ZERO_ROOT is defined and the class lands in the site's entity/ folder; a second run throws because the class file exists. The call writes entity/Product.php, inserts the entity_type row, adds the partition, writes the six schema rows, stores one record of nulls and creates product_view. From then on, use the generated class:

use Zero\Entity\Product;

// Create — status, stock and created_at come from the defaults
$p = new Product([
    'name'  => 'Burnt Orange Candle',
    'price' => '22.00',
    'sku'   => 'CND-BRN-01',
]);
echo $p->id;

// Find
$p = Product::getInstance()->where('sku', 'CND-BRN-01');

// Update
$p->price = '24.00';           // immediate REPLACE INTO
$p->status = 'discontinued';   // another immediate write

// Browse via the pivot view
$db = \Zero\Core\Database::getConnection();
$rows = $db->query("SELECT id, name, price FROM product_view WHERE status = 'active' ORDER BY created_at DESC")->fetchAll();

Example 4 — SessionLog: Defaults Showcase

Every kind of default at once, for reference:

\Zero\Entity\GenericEntity::define('session_log', [
    'attributes' => ['token', 'ip', 'user_agent', 'status', 'created_at'],
    'defaults'   => [
        'token'      => 'uniqid:sess_',         // uniqid('sess_')
        'ip'         => 'server:REMOTE_ADDR',   // $_SERVER['REMOTE_ADDR'] ?? null
        'user_agent' => 'server:HTTP_USER_AGENT',
        'status'     => 'active',               // literal string
        'created_at' => 'date:Y-m-d H:i:s',     // date('Y-m-d H:i:s', time())
    ],
]);

// In later requests — all defaults apply, only explicit keys need to be passed:
new \Zero\Entity\SessionLog([]);

The class is SessionLog, so the label is sessionlog and the view is sessionlog_view: the underscore in the type name does not survive. See Default Values for the generated constructor.

Example 5 — Defensive where()

Every realistic use of where() has three branches:

use Zero\Entity\Product;

function findProductBySku(string $sku): ?Product {
    $r = Product::getInstance()->where('sku', $sku);

    if ($r === null) {
        return null;
    }
    if (is_array($r)) {
        // Several products with one sku: $uniq is a check, not a constraint.
        // Log and pick the earliest by id so callers still get a usable object.
        \Zero\Core\Console::warn("duplicate products for sku {$sku}");
        usort($r, fn($a, $b) => (int) $a->id <=> (int) $b->id);
        return $r[0];
    }
    return $r;
}

Example 6 — When Not to Use It

Core's own accounts are the counter-example. A user is Zero\Core\Access\User (core/access/User.php), a Zero\Core\Model over the users table, because an email address needs a real UNIQUE KEY and $uniq cannot give one. When a type needs typed columns, a constraint, a join or a value over 255 characters, give it a table of its own. See Models.

Further Reading