Skip to content
Belikhun edited this page Sep 15, 2026 · 1 revision

🧱 Model

A model maps a class to a table. It fills itself from rows, saves back only what changed, deletes transactionally, and announces its changes as Lightrail events.

Declaring one

namespace App\Model;

use Blink\Model;

/**
 * @extends parent<static>
 */
class Order extends Model {
	public static string $table = "orders";

	public static $fillables = array(
		"id",
		"customer" => "customer_id",
		"reference",
		"total",
		"status",
		"created",
		"updated"
	);

	public int $id;
	public int $customer;
	public string $reference;
	public float $total;
	public string $status = "draft";
	public int $created;
	public int $updated;
}

$fillables maps properties to columns; a bare name means the two match. created and updated are stamped for you. The primary key is id unless $primaryKey says otherwise.

The @extends parent<static> line is for your editor: it makes Order::query() -> first() resolve to an Order.

Reading

Order::getByID(42);                           // Order, or null
Order::getByID(42, Model::MUST_EXIST);        // throws ModelInstanceNotFound
Order::getByIDs([ 1, 2, 3 ]);                 // Order[], missing ids skipped
Order::all();

Order::where(Order::col("status"), "paid") -> all();
Order::query()
	-> where(Order::col("total"), ">=", 100)
	-> sort(Order::col("created"), "DESC")
	-> all(0, 20);

Order::col("property") names a column by its property, Order::col("#") the primary key, Order::t() the table for joins. Everything the query engine offers applies; see Query Engine.

Instances are cached per class and id for the request, so two getByID(42) calls return the same object. Order::preload([ ... ]) fetches many in one query ahead of time.

Writing

$order = Order::create(array( "customer" => $customer -> id, "reference" => "A-17", "total" => 120 ));
$order -> save();

$order -> status = "paid";
$order -> save();

$order -> increase("total", 5);     // atomic, in the database
$order -> delete();

save() inserts when the instance has no primary key and updates otherwise. An update writes only the properties whose save value differs from the snapshot taken when the instance was loaded; isDirty() and isClean() ask the same question.

Deleting

delete() runs inside a transaction together with everything beforeDelete() removes. If any step throws, the transaction rolls back and every in-memory instance that was deleted along the way is restored, so the objects you hold match the database again. Nested deletions share the outermost transaction.

canDelete() returns [bool, int]: whether deletion is safe to do without confirmation, and how many other records would go with it.

Hooks

Hook Called
onLoaded() After an instance is filled from a row
beforeSave() Before an insert or update
onCreated() After an insert
onSaved() After an insert or update
beforeDelete(?ProgressReporter $reporter) Before the delete, inside its transaction
onDeleted(?ProgressReporter $reporter) After the delete
protected function beforeDelete(?ProgressReporter $reporter = null) {
	foreach (Item::where(Item::col("order"), $this -> id) -> all() as $item)
		$item -> delete();
}

Field conversion

A column that stores something other than a scalar converts on the way in and out:

public ?array $meta = null;

protected static function processField(string $name, $value) {
	return match ($name) {
		"meta" => $value ? json_decode($value, true) : null,
		default => parent::processField($name, $value)
	};
}

protected function saveField(string $name) {
	return match ($name) {
		"meta" => $this -> meta !== null ? json_encode($this -> meta) : null,
		default => parent::saveField($name)
	};
}

Lazy loading

A property holding another model would cost a query per row. Mark it lazy and the query runs only when the property is first read:

use Blink\Attribute\Lazyload;

/**
 * @property Customer $customer
 */
class Order extends Model {
	#[Lazyload("customer")]
	protected Customer $__customer;

	protected static function processField(string $name, $value) {
		return match ($name) {
			"customer" => Customer::getByID($value, Model::MUST_EXIST),
			default => parent::processField($name, $value)
		};
	}

	protected function saveField(string $name) {
		return match ($name) {
			"customer" => $this -> customer -> id,
			default => parent::saveField($name)
		};
	}
}

The real property is prefixed __ and cannot be private; the @property line keeps your editor informed. Reading $order -> customer triggers the load. invalidateLazyloadProperty("customer") forgets a loaded value.

Sensitive fields

use Blink\Attribute\SensitiveField;

#[SensitiveField]
public string $passwordHash;

A sensitive property is left out of out(), jsonSerialize(), get() and json_encode() unless asked for with sensitive: true. Reading the property directly still works.

Serializing

$order -> out();                     // array, nested models included
$order -> out(depth: 1);             // nested models as ids
$order -> jsonSerialize();           // the same, what json_encode() calls
$order -> toRecord();                // the row as it would be written

Events

Every save and delete emits a Lightrail event carrying the model class and the row id:

Event When Extra context
Blink\Event\ModelCreated After an insert changes, every field from null
Blink\Event\ModelUpdated After an update that changed something changes as field => [old, new]
Blink\Event\ModelSaved After either changes
Blink\Event\ModelDeleted After a delete changes, every field to null
use Blink\Event\ModelUpdated;
use Blink\Lightrail\Attribute\Context;
use Blink\Lightrail\Attribute\Observe;

class OrderObserver {
	#[Observe(ModelUpdated::class)]
	#[Context([ "model" => Order::class ])]
	public static function onOrderChanged(ModelUpdated $event): void {
		if ($event -> changed("status"))
			Notifier::orderStatus($event -> instanceID(), $event -> changes()["status"]["new"]);
	}
}

modelClass(), instanceID(), changes() and changed(...$fields) read the context. Lightrail's own trail models and Trace's entries emit nothing, so an observer never sees the bookkeeping its own run produces.

Blink\Observer\ModelAuditObserver listens to these three events and writes the audit log; see Trace.

The user class

Blink has no user table of its own. An application extends Blink\Model\UserBase, which requires id, username and a static getByUsername(), and registers it from a module's define():

\Blink::useUserClass(App\Model\User::class);

Session, Token and Trace resolve the current user through it. Without a registration, Blink::userClass() raises a CodingError and the error page's tip says what to add.

Clone this wiki locally