DB

object

%DB

/phlo/resources/DB/DB.phlo

Database engine class

The shape every driver fills in, and the reason a model can move between MySQL, PostgreSQL, SQLite and a JSON file untouched. Reads come in named flavours, so ask for what you want back: record for one, records keyed by id, rows in order, column, pair and item. Anything you pass as an argument is bound, never pasted into the SQL, so a value from a visitor is safe by construction. A connection that went away is reconnected and the query is tried once more, which is what keeps a long-lived worker alive.

databasepdosql
prop

%DB -> PDO:\PDO

line 12
Deze functie genereert een fout als er geen PDO-connector is gedefinieerd voor databasebewerkingen.
error('No PDO connector defined')
prop

%DB -> fieldQuotes:string

line 13
Haal de veldcitaten op voor een specifiek databaseveld, zodat de SQL-query's correct worden opgemaakt.
bt
prop

%DB -> savepoint:int

line 14
Maakt een savepoint in de huidige database-transactie, waardoor gedeeltelijke terugdraaien mogelijk is.
prop

%DB -> insertIgnore:string

line 15
Voegt een nieuw record toe aan de database en negeert eventuele dubbele invoeren die een conflict zouden veroorzaken.
' IGNORE'
prop

%DB -> insertOnConflict:string

line 16
Voegt een nieuw record toe aan de database en werkt het bestaande record bij in geval van een conflict.
void
method

%DB -> load (string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, ...$args)

line 18
Laadt gegevens uit de opgegeven tabel in de database, met de mogelijkheid om optioneel kolommen te selecteren, te filteren met voorwaarden, te koppelen aan andere tabellen, te groeperen, te sorteren en de resultaten te beperken.
$table = strpos($table, space) || strpos($table, dot) ? $table : "$this->fieldQuotes$table$this->fieldQuotes"
$args && $where = ($where ? "$where AND " : void).loop(array_keys($args), fn($column) => $table.dot.$this->quoteId($column).'=?', ' AND ')
$joins && $joins = " $joins"
$where && $where = " WHERE $where"
$group && $group = " GROUP BY $group"
$order && $order = " ORDER BY $order"
$limit && $limit = " LIMIT $limit"
$query = "SELECT $columns FROM $table$joins$where$group$order$limit"
return $this->query($query, ...array_values($args))
method

%DB -> query ($query, ...$args)

line 30
Voert een databasequery uit met de opgegeven SQL-instructie en argumenten, en retourneert de resultaten.
$this->queryRun($query, $args, true)
method

%DB -> queryRun ($query, $args, $retry):\PDOStatement

line 37
Runs a statement, retrying once when the connection was lost.
try {
	if (!$args) $stmt = $this->PDO->query($query)
	else {
		$stmt = $this->PDO->prepare($query)
		$stmt->execute($args)
	}
	if (debug){
		$match = regex('/\b(UPDATE|INSERT INTO|DELETE FROM|FROM)\b\s+([`"\[]?\w+[`"\]]?)/i', strtr($query, [$this->fieldQuotes => void]))
		$where = strtr(regex('/\bWHERE (\b.+)/is', $query)[1] ?? void, [' ORDER BY' => void])
		$match && debug("Q: $match[1] $match[2]".strtr(rtrim(" $where "), [dq => void])." (".$stmt->rowCount().")")
	}
	return $stmt
}
catch (\PDOException $e){
	// Retry only idempotent read statements outside a transaction. WITH is excluded: a `WITH ... UPDATE`
	// or `WITH ... DELETE` CTE is a mutation that may already have run before the connection dropped
	// (error 2013), and a reconnect would start a fresh, transaction-less session.
	if (!$retry || !$this->goneAway($e) || $this->PDO->inTransaction() || !preg_match('/^\s*\(*\s*(SELECT|SHOW|EXPLAIN|DESCRIBE|DESC)\b/i', $query)) error('Database error'.colon.lf.$query.lf.lf.$e->getMessage())
	unset($this->PDO)
	return $this->queryRun($query, $args, false)
}
method

%DB -> goneAway ($e):bool

line 61
Controleert of een databaseverbindingfout aangeeft dat de verbinding is verloren of de server niet beschikbaar is.
in_array((int)($e->errorInfo[1] ?? 0), [2006, 2013], true) || stripos($e->getMessage(), 'gone away') !== false || stripos($e->getMessage(), 'lost connection') !== false
method

%DB -> column (...$args):array

line 63
Haalt een enkele kolom op uit de resultaten van een databasequery, met behulp van de opgegeven argumenten om de gegevens te laden.
$this->load(...$args)->fetchAll(\PDO::FETCH_COLUMN)
method

%DB -> item (...$args)

line 64
Laadt een item uit de database met de opgegeven argumenten en retourneert het als een enkele kolomwaarde, of null als het niet is gevonden.
($v = $this->load(...$args)->fetch(\PDO::FETCH_COLUMN)) === false ? null : $v
method

%DB -> pair (...$args):array

line 65
Haalt alle rijen uit de database op als een sleutel-waarde paar array met de opgegeven argumenten.
$this->load(...$args)->fetchAll(\PDO::FETCH_KEY_PAIR)
method

%DB -> group (...$args):array

line 66
Haal alle records uit de database op, gegroepeerd op een opgegeven kolom of kolommen, en retourneer de resultaten als een array van objecten van de opgegeven klasse.
$this->load(...$args)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_CLASS, obj::class)
method

%DB -> records (...$args):array

line 67
Haalt alle records uit de database op als objecten van de opgegeven klasse, met behulp van de meegeleverde argumenten voor de query.
$this->load(...$args)->fetchAll(\PDO::FETCH_CLASS|\PDO::FETCH_UNIQUE, obj::class)
method

%DB -> rows (...$args):array

line 68
Haalt alle rijen uit de database op als instanties van de opgegeven klasse met behulp van de meegeleverde argumenten.
$this->load(...$args)->fetchAll(\PDO::FETCH_CLASS, obj::class)
method

%DB -> record (...$args):?obj

line 69
Haal een enkel record uit de database op als een object van de opgegeven klasse, en retourneer null als er geen record wordt gevonden.
$this->load(...$args)->fetchObject(obj::class) ?: null
method

%DB -> quoteList (array $ids):string

line 70
Quote elk element in de opgegeven array van ID's voor veilig gebruik in SQL-query's, en retourneert een door komma's gescheiden string.
loop($ids, fn($id) => $this->PDO->quote((string)$id), comma)
method

%DB -> quoteId ($id):string

line 75
Safely quotes a SQL identifier such as a column or table name.
$this->fieldQuotes.str_replace($this->fieldQuotes, $this->fieldQuotes.$this->fieldQuotes, (string)$id).$this->fieldQuotes
method

%DB -> create (string $table, ...$data)

line 77
Voegt een nieuw record toe aan de opgegeven tabel met de verstrekte gegevens, waarbij conflicten optioneel worden genegeerd op basis van de 'ignore'-vlag.
if ($ignore = $data['ignore'] ?? false) unset($data['ignore'])
$columns = implode(comma, loop(array_keys($data), fn($k) => $this->quoteId($k)))
$values = implode(comma, array_fill(0, count($data), qm))
$query = "INSERT".($ignore ? $this->insertIgnore : void)." INTO $table ($columns) VALUES ($values)".($ignore ? $this->insertOnConflict : void)
$this->query($query, ...array_values(loop($data, fn($value) => is_a($value, obj::class) ? $value->id : $value)))
return $this->lastId() ?: ($data['id'] ?? null)
method

%DB -> lastId

line 86
Geeft de ID van de laatst ingevoegde rij in de database terug.
$this->PDO->lastInsertId()
method

%DB -> change (string $table, string $where, ...$data):int

line 88
Werk records bij in de opgegeven tabel op basis van de gegeven voorwaarden en gegevens.
$whereCount = substr_count($where, qm)
$updates = isset($data['updates']) ? $data['updates'] : void
unset($data['updates'])
$updates .= (($wheres = array_slice(array_keys($data), $whereCount)) && $updates ? comma : void).loop($wheres, fn($key) => $this->quoteId($key).'=?', comma)
$query = "UPDATE $table SET $updates WHERE $where"
$args = array_values([...array_slice($data, $whereCount), ...array_slice($data, 0, $whereCount)])
return $this->query($query, ...$args)->rowCount()
method

%DB -> delete (string $table, string $where, ...$args):int

line 98
Verwijdert rijen uit de opgegeven tabel op basis van de gegeven voorwaarde. Het retourneert het aantal aangetaste rijen.
$this->query("DELETE FROM $table WHERE $where", ...$args)->rowCount()
method

%DB -> begin:?bool

line 99
Start een nieuwe database transactie met PDO.
$this->PDO->beginTransaction()
method

%DB -> commit:?bool

line 100
Bevestigt de huidige transactie in de database, waardoor alle wijzigingen die tijdens de transactie zijn aangebracht permanent worden.
$this->PDO->commit()
method

%DB -> rollback:?bool

line 101
Rol de huidige transactie terug als deze actief is, waardoor alle wijzigingen die tijdens de transactie zijn aangebracht, ongedaan worden gemaakt.
$this->PDO->inTransaction() && $this->PDO->rollBack()
method

%DB -> transaction ($callback)

line 103
Voert een database-transactie uit, waarbij een callbackfunctie binnen de transactiecontext kan worden uitgevoerd. Als er een fout optreedt, wordt er teruggekeerd naar het laatste savepoint of het begin van de transactie, wat de gegevensintegriteit waarborgt.
if (!$this->PDO->inTransaction()){
	$this->begin
	try {
		$result = $callback()
		$this->commit
		return $result
	} catch (\Throwable $e){
		$this->rollback
		throw $e
	}
}
// Nested: a savepoint gives the inner unit its own rollback point, so its failure
// (e.g. an audit insert) is undone even when the outer transaction commits.
$sp = 'phlo_sp_'.(++$this->savepoint)
$this->PDO->exec('SAVEPOINT '.$sp)
try {
	$result = $callback()
	$this->PDO->exec('RELEASE SAVEPOINT '.$sp)
	$this->savepoint--
	return $result
} catch (\Throwable $e){
	$this->PDO->exec('ROLLBACK TO SAVEPOINT '.$sp)
	$this->PDO->exec('RELEASE SAVEPOINT '.$sp)
	$this->savepoint--
	throw $e
}
object

%JSONDB

/phlo/resources/DB/JSONDB.phlo

JSON file database driver. One JSONDB instance = one JSON file = one model table. No joins, no transactions, no schema introspection.

A model in a JSON file, for a set of records that stays small and readable: no joins, no transactions, and every write rewrites the whole file. It understands only equality and IN in a where, and raw SQL is refused outright, so keep the model plain. Move to SQLite the moment the file grows or two processes start writing.

jsondatabasefilestorage
static

JSONDB :: __handle

line 12
JSONDB::$__handle is een verwijzing naar de interne bestandsverwijzing die wordt gebruikt voor het openen van de JSON-database die is opgegeven door het $file-pad.
"JSONDB/$file"
method

%JSONDB -> __construct (private string $file)

line 13
De constructor initialiseert een JSONDB-instantie en zorgt ervoor dat de map voor het opgegeven bestand bestaat, en maakt deze indien nodig aan.
$dir = dirname($this->file)
is_dir($dir) || mkdir($dir, 0755, true) || error("JSONDB: cannot create dir $dir")
prop

%JSONDB -> PDO:\PDO

line 17
Deze functie genereert een foutmelding die aangeeft dat de JSONDB-driver niet compatibel is met PDO.
error('JSONDB driver does not use PDO')
prop

%JSONDB -> fieldQuotes:string

line 18
Haal de citaten op voor een specifiek veld in een JSONDB-resource.
void
prop

%JSONDB -> lastInsertedId

line 19
Geeft de ID van het laatst ingevoegde record in de JSONDB.
null
method

%JSONDB -> quoteList (array $ids):string

line 26
Builds the quoted id list an IN clause expects.
dq.implode(dq.comma.dq, $ids).dq
method

%JSONDB -> objRead:array

line 28
Leest een JSON-bestand en retourneert de inhoud als een associatieve array. Als het bestand niet bestaat of leeg is, retourneert het een lege array.
file_exists($this->file) ? json_decode(file_get_contents($this->file), true) ?: [] : []
method

%JSONDB -> objWrite (array $data):int|false

line 29
file_put_contents($this->file, json_encode(array_values($data), jsonPretty), LOCK_EX)
method

%JSONDB -> objNextId (array $data):int

line 30
Geeft de volgende beschikbare ID voor een nieuw object in de gegeven array van gegevens door de maximale huidige ID te vinden en er één bij op te tellen, of retourneert 1 als de array leeg is.
$data ? (int)max(array_column($data, 'id')) + 1 : 1
method

%JSONDB -> objFilter (array $data, string $where = void, ...$args):array

line 32
Filtert een array van gegevens op basis van opgegeven voorwaarden in de 'where'-clausule en retourneert alleen de overeenkomende rijen.
if (!$where) return $data
$filtered = []
foreach ($data AS $row){
	$match = true
	$parts = preg_split('/\s+AND\s+/i', $where)
	$argIndex = 0
	foreach ($parts AS $part){
		if (preg_match('/^[`"]?(\w+)[`"]?\s*=\s*\?$/', trim($part), $m)){
			$column = $m[1]
			$value = $args[$argIndex++] ?? null
			if (($row[$column] ?? null) != $value) $match = false
		}
		elseif (preg_match('/^[`"]?(\w+)[`"]?\s+IN\s*\((.+)\)$/i', trim($part), $m)){
			$column = $m[1]
			$ids = array_map(fn($v) => trim($v, "\"' "), explode(comma, $m[2]))
			if (!in_array($row[$column] ?? null, $ids)) $match = false
		}
	}
	$match && $filtered[] = $row
}
return $filtered
method

%JSONDB -> objSelect (string $where = void, string $limit = void, string $order = void, ...$args):array

line 56
Selecteert objecten uit de JSON-database op basis van opgegeven voorwaarden, met optionele sortering en beperking van de resultaten.
$data = $this->objFilter($this->objRead(), $where, ...array_values($args))
if ($order){
	$desc = str_contains($order, 'DESC')
	$col = trim(preg_replace('/\s+(ASC|DESC)/i', void, $order), '` ')
	usort($data, fn($a, $b) => $desc ? ($b[$col] ?? 0) <=> ($a[$col] ?? 0) : ($a[$col] ?? 0) <=> ($b[$col] ?? 0))
}
$limit && $data = array_slice($data, 0, (int)$limit)
return $data
method

%JSONDB -> create (string $table, ...$data)

line 70
ignore compares ids loosely, so the string "7" and the number 7 count as one row.
if ($ignore = $data['ignore'] ?? false) unset($data['ignore'])
$all = $this->objRead()
$data['id'] ??= $this->objNextId($all)
foreach ($data AS $key => $value) is_a($value, 'obj') && $data[$key] = $value->id
if ($ignore){
	foreach ($all AS $row) if (($row['id'] ?? null) == $data['id']) return $data['id']
}
$all[] = $data
$this->objWrite($all)
$this->lastInsertedId = $data['id']
return $data['id']
method

%JSONDB -> change (string $table, string $where, ...$data):int

line 84
Werk rijen in de opgegeven tabel bij die voldoen aan de gegeven voorwaarde met nieuwe gegevens en retourneer het aantal gewijzigde rijen.
$all = $this->objRead()
$whereCount = substr_count($where, qm)
$whereArgs = array_slice(array_values($data), 0, $whereCount)
$updates = array_slice($data, $whereCount, null, true)
$changed = 0
foreach ($all AS &$row){
	if ($this->objFilter([$row], $where, ...$whereArgs)){
		foreach ($updates AS $key => $value) $row[$key] = $value
		$changed++
	}
}
unset($row)
$this->objWrite($all)
return $changed
method

%JSONDB -> delete (string $table, string $where, ...$args):int

line 101
Verwijdert records uit de opgegeven tabel in de JSON-database die voldoen aan de gegeven voorwaarde.
$all = $this->objRead()
$matching = $this->objFilter($all, $where, ...$args)
$matchIds = array_column($matching, 'id')
$remaining = array_values(array_filter($all, fn($row) => !in_array($row['id'] ?? null, $matchIds)))
$this->objWrite($remaining)
return count($matching)
method

%JSONDB -> load (string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, ...$args):JSON_result

line 110
Laadt gegevens uit een opgegeven tabel in JSONDB, met de mogelijkheid om optioneel kolommen te selecteren, te filteren met voorwaarden, te koppelen aan andere tabellen, te groeperen, resultaten te beperken en te ordenen.
!$where && $args && $where = loop(array_keys($args), fn($column) => "$column=?", ' AND ')
$data = $this->objSelect($where, $limit, $order, ...array_values($args))
return %JSON_result($data)
method

%JSONDB -> query ($query, ...$args)

line 115
Voert een query uit tegen de JSONDB, maar ondersteunt geen ruwe SQL-queries.
error('JSONDB driver does not support raw SQL queries')
method

%JSONDB -> begin:?bool

line 117
Begint een transactie in de JSONDB, waardoor meerdere bewerkingen atomair kunnen worden uitgevoerd.
null
method

%JSONDB -> commit:?bool

line 118
Bevestigt de huidige transactie in de JSONDB en slaat alle wijzigingen op die tijdens de transactie zijn aangebracht.
null
method

%JSONDB -> rollback:?bool

line 119
Herstelt de laatste transactie in de JSONDB en brengt de database terug naar de vorige staat.
null
object

%JSON_result

/phlo/resources/DB/JSON.result.phlo

Minimal PDOStatement-like wrapper for JSONDB result arrays

Exists so JSONDB can hand back something that behaves like a PDO statement, which is what lets the ORM stay unaware of which driver answered. You do not build one yourself; you meet it as the return value of a JSONDB query.

jsondatabaseresult
static

JSON_result :: __handle

line 10
Deze eigenschap wordt gebruikt om toegang te krijgen tot de interne handle van een JSON_result-object.
null
prop

%JSON_result -> data:array

line 11
Toegang tot de `$data`-eigenschap van het `JSON_result`-object, dat de geparsed gegevens van een JSON-respons bevat.
[]
method

%JSON_result -> __construct (array $data)

line 12
Initialiseert een JSON_result-object met de opgegeven gegevensarray.
$this->data = $data
method

%JSON_result -> fetchAll ($mode = 2, $class = 'obj'):array

line 14
if ($mode === \PDO::FETCH_COLUMN) return loop($this->data, fn($row) => reset((array)$row))
if ($mode === \PDO::FETCH_KEY_PAIR){
	$out = []
	foreach ($this->data AS $row){
		$vals = array_values((array)$row)
		$out[$vals[0] ?? null] = $vals[1] ?? null
	}
	return $out
}
if (($mode & (\PDO::FETCH_CLASS | \PDO::FETCH_UNIQUE)) === (\PDO::FETCH_CLASS | \PDO::FETCH_UNIQUE)){
	$out = []
	foreach ($this->data AS $row){
		$o = new $class
		foreach ((array)$row AS $k => $v) $o->$k = $v
		$out[$row['id'] ?? count($out)] = $o
	}
	return $out
}
if (($mode & \PDO::FETCH_CLASS) === \PDO::FETCH_CLASS){
	$out = []
	foreach ($this->data AS $row){
		$o = new $class
		foreach ((array)$row AS $k => $v) $o->$k = $v
		$out[] = $o
	}
	return $out
}
return $this->data
method

%JSON_result -> fetchObject ($class = 'obj'):?obj

line 45
Haal een enkel object van de opgegeven klasse op uit de JSON-resultaatgegevens, waarbij de eigenschappen van het object worden gekoppeld aan de waarden in de eerste rij van de gegevens.
if (!$this->data) return null
$row = reset($this->data)
$o = new $class
foreach ((array)$row AS $k => $v) $o->$k = $v
return $o
method

%JSON_result -> fetch ($mode = 2)

line 53
Haal een resultaatrij op uit de JSON-gegevens, waarbij ofwel de hele rij of een specifieke kolom wordt geretourneerd op basis van de opgegeven modus.
if (!$this->data) return null
$row = reset($this->data)
if ($mode === \PDO::FETCH_COLUMN) return reset((array)$row)
return $row
method

%JSON_result -> fetchColumn ($col = 0)

line 60
Haal een enkele kolom op uit de eerste rij van de JSON-resultaatset en retourneer de waarde op de opgegeven kolomindex of false als deze niet is gevonden.
if (!$this->data) return false
$row = reset($this->data)
$vals = array_values((array)$row)
return $vals[$col] ?? false
method

%JSON_result -> rowCount:int

line 67
Geeft het aantal rijen in de JSON-resultaatset terug.
count($this->data)
object

%model

/phlo/resources/DB/model.phlo

Phlo ORM class with unified columns and schema

A model is a class with fields, and everything else follows from that: columns, form, validation and relations. Named arguments in a read are equality, so records(active: 1) is a where and nothing more; reach for query() when you need a comparison, a LIKE or an IN. A parent field gives back the record itself rather than an id, and children and many-relations are fetched once for a whole result set instead of per row. Set objValidate to have field rules enforced on save, objAudit to log every change, and objCache to keep reads in APCu.

ormmodeldatabaserecordsschema
static

model :: DB

line 12
Deze eigenschap geeft toegang tot de database-engineconfiguratie voor het model en genereert een fout als er geen is geconfigureerd.
error('No database engine configured for '.static::class)
static

model :: objCache

line 13
De model::$objCache-eigenschap bevat een cache voor modelobjecten, waardoor de prestaties worden verbeterd door de noodzaak om dezelfde gegevens herhaaldelijk op te halen te verminderen.
false
static

model :: objRecordLimit

line 14
Stelt het maximale aantal records in dat door het model kan worden opgehaald.
10000
static

model :: objAudit

line 15
De `model::$objAudit` eigenschap wordt gebruikt om het auditobject dat aan het model is gekoppeld te benaderen, waardoor het mogelijk is om wijzigingen en aanpassingen bij te houden.
false
static

model :: objValidate

line 16
De model::$objValidate-eigenschap geeft aan of de objectvalidatie is in- of uitgeschakeld, en retourneert false als de validatie niet actief is.
false
static

model :: idColumn

line 17
De model::$idColumn-eigenschap geeft de naam van de identificatiekolom aan die in het model wordt gebruikt, standaard 'id'.
'id'
static

model :: idType

line 18
Definieert het gegevenstype voor de identifier van het model als een geheel getal.
'int'
static

model :: canView

line 20
Deze eigenschap geeft aan of de huidige gebruiker toestemming heeft om het model te bekijken.
true
static

model :: canCreate

line 21
De model::$canCreate-eigenschap geeft aan of er een nieuwe instantie van het model kan worden gemaakt.
true
static

model :: canChange

line 22
Deze eigenschap geeft aan of het model kan worden gewijzigd, en retourneert true als wijzigingen zijn toegestaan.
true
static

model :: canDelete

line 23
De model::$canDelete-eigenschap geeft aan of de modelinstantie kan worden verwijderd.
true
static

model :: state:obj

line 25
De `model::$state` eigenschap bevat de huidige staat van het model, inclusief metadata, records en fouten.
%req->model ??= obj(meta: [], records: [], errors: [])
static

model :: columns:string

line 26
Haal de kolommen op die in het model zijn gedefinieerd, hetzij vanuit de static::$columns-eigenschap of door de schema-methode aan te roepen als deze bestaat.
if (isset(static::$columns)) return static::$columns
if (!method_exists(static::class, 'schema')) return static::$table.'.*'
$state = static::state()
$key = spl_object_id(static::DB()).':'.static::DB()->fieldQuotes.':'.static::$table
return $state->meta[static::class]['columns'][$key] ??= static::_columns()
static

model :: _columns:string

line 33
Haal de kolomnamen op van de bijbehorende database-tabel van het model, geformatteerd met veldquotes.
$fq = static::DB()->fieldQuotes
$list = array_merge(...array_values(array_filter(loop(static::fields(), fn($field) => loop($field->objColumns, fn($col) => static::$table."$fq.$fq".$col)))))
return $fq.implode("$fq,$fq", $list).$fq
static

model :: fields:array

line 38
Geeft de velden terug die zijn gedefinieerd in het schema van het model, of een lege array als er geen schema bestaat. Als het schema beschikbaar is, worden de velden opgehaald uit de metadata van de status van het model.
if (!method_exists(static::class, 'schema')) return static::$fields ?? []
$state = static::state()
return $state->meta[static::class]['fields'] ??= static::_fields()
static

model :: _fields:array

line 43
Deze eigenschap haalt de velden op die in het schema van het model zijn gedefinieerd, waarbij wordt gegarandeerd dat geen van de veldnamen in conflict komt met gereserveerde trefwoorden.
$reserved = ['table','order','fields','columns','create','change','delete','records','record','column','item','pair','DB','objCache','objState','objSave','objGet','objAudit','objValidate','objErrors','idColumn','idType']
$fields = loop(static::schema(), fn($field, $column) => last($field->name ??= $column, $field->type === 'parent' && $field->obj ??= $column, $field))
foreach ($reserved AS $word) isset($fields[$word]) && error("Reserved column name '$word' in ".static::class)
return $fields
static

model :: field ($name)

line 49
Toegang tot een specifiek veld dat is gedefinieerd in de statische veldenarray van het model met de opgegeven naam.
static::fields()[$name]
static

model :: create (...$args):?static

line 51
Maakt een nieuwe instantie van het model, valideert de invoerargumenten en voert eventuele gedefinieerde levenscyclusmethoden uit voordat het record in de database wordt opgeslagen.
$class = static::class
if (static::objValidate() && !static::objRunValidation($args)) return null
$record = new $class(...$args)
method_exists(static::class, 'beforeSave') && $record->beforeSave()
method_exists(static::class, 'beforeCreate') && $record->beforeCreate()
$pk = static::idColumn()
return static::objAudit() ? static::transaction(fn() => static::objCreateCommit($record, $pk)) : static::objCreateCommit($record, $pk)
static

model :: objCreateCommit ($record, $pk):?static

line 61
Maakt een nieuw record in het model en activeert de afterCreate- en afterSave-methoden als ze bestaan, terwijl ook de creatieactiviteit voor auditdoeleinden wordt vastgelegd.
$id = static::createRecord(...$record)
$record = static::record(...[$pk => $record->$pk ?? $id])
method_exists(static::class, 'afterCreate') && $record->afterCreate()
method_exists(static::class, 'afterSave') && $record->afterSave()
static::objAudit() && audit::log($record, 'create', [], $record->objData)
return $record
static

model :: objRunValidation ($data):bool

line 70
Valideert de verstrekte gegevens tegen de gedefinieerde velden van het model en verzamelt eventuele fouten die tijdens het validatieproces worden aangetroffen.
$errors = []
$fields = static::fields()
foreach ($data AS $column => $value){
	if (!($field = $fields[$column] ?? null) || !method_exists($field, 'objValidate')) continue
	if ($error = $field->objValidate($value)) $errors[$column] = $error
}
static::state()->errors[static::class] = $errors
return empty($errors)
static

model :: objErrors:array

line 81
Haal de foutmeldingen op die zijn gekoppeld aan de huidige modelinstantie, en retourneer een lege array als er geen zijn gevonden.
static::state()->errors[static::class] ?? []
static

model :: createRecord (...$args)

line 82
Maakt een nieuw record aan in de opgegeven database tabel met de meegeleverde argumenten.
static::DB()->create(static::$table, ...$args)
static

model :: change ($where, ...$args):int

line 83
Deze methode behandelt de wijzigingsoperatie voor een model, voert indien nodig een audit uit en logt updates naar de database.
if (!static::objAudit()) return static::DB()->change(static::$table, $where, ...$args)
$pk = static::idColumn()
$bindings = array_values(array_filter($args, 'is_int', ARRAY_FILTER_USE_KEY))
return static::transaction(function() use ($where, $args, $bindings, $pk){
	$old = static::DB()->query('SELECT '.static::$table.'.* FROM '.static::$table.' WHERE '.$where, ...$bindings)->fetchAll(\PDO::FETCH_CLASS, static::class)
	$result = static::DB()->change(static::$table, $where, ...$args)
	foreach ($old AS $record){
		$fresh = static::record(...[$pk => $record->$pk])
		$fresh && audit::log($fresh, 'update', $record->objData, $fresh->objData)
	}
	return $result
})
static

model :: delete ($where, ...$args):int

line 98
Verwijdert records uit de database-tabel die aan het model is gekoppeld, waarbij de methoden 'beforeDelete' en 'afterDelete' worden aangeroepen als ze bestaan, en waarbij auditing en transacties indien nodig worden afgehandeld.
if (method_exists(static::class, 'beforeDelete') || method_exists(static::class, 'afterDelete') || static::objAudit()){
	$records = static::DB()->query('SELECT '.static::$table.'.* FROM '.static::$table.' WHERE '.$where, ...$args)->fetchAll(\PDO::FETCH_CLASS, static::class)
	foreach ($records AS $record) method_exists(static::class, 'beforeDelete') && $record->beforeDelete()
	return static::objAudit() ? static::transaction(fn() => static::objDeleteCommit($where, $args, $records)) : static::objDeleteCommit($where, $args, $records)
}
return static::DB()->delete(static::$table, $where, ...$args)
static

model :: objDeleteCommit ($where, $args, $records):int

line 107
Verwijdert een record uit de database op basis van de opgegeven voorwaarden en voert een optionele na-verwijdermethode uit voor elk record, waarbij de verwijdering wordt gelogd als auditing is ingeschakeld.
$result = static::DB()->delete(static::$table, $where, ...$args)
foreach ($records AS $record){
	method_exists(static::class, 'afterDelete') && $record->afterDelete()
	static::objAudit() && audit::log($record, 'delete', $record->objData, [])
}
return $result
static

model :: objLogChange ($where, ...$args):int

line 116
Logt wijzigingen aan het opgegeven modelobject, waarbij de staat voor en na de aanpassingen wordt vastgelegd.
static::change($where, ...$args)
method

%model -> objSave:?static

line 118
$pk = static::idColumn()
$pkValue = $this->$pk ?? $this->id ?? null
$pkValue || error('Can\'t save '.static::class.' record without '.$pk)
$old = static::record(...[$pk => $pkValue])
$isNew = !$old
method_exists(static::class, 'beforeSave') && $this->beforeSave($old)
if ($isNew){
	method_exists(static::class, 'beforeCreate') && $this->beforeCreate()
	$saved = static::objAudit() ? static::transaction(fn() => $this->objSaveCreate($pk, $pkValue)) : $this->objSaveCreate($pk, $pkValue)
}
else {
	method_exists(static::class, 'beforeChange') && $this->beforeChange($old)
	static::change($pk.'=?', $pkValue, ...$this)
	$saved = static::record(...[$pk => $pkValue])
	method_exists(static::class, 'afterChange') && $saved->afterChange($old)
}
method_exists(static::class, 'afterSave') && $saved->afterSave($old)
return $saved
method

%model -> objSaveCreate ($pk, $pkValue):?static

line 139
Maakt een nieuw record in het model en voert post-creatieacties uit indien gedefinieerd, zoals loggen en auditen.
static::createRecord(...$this)
$saved = static::record(...[$pk => $pkValue])
method_exists(static::class, 'afterCreate') && $saved->afterCreate()
static::objAudit() && audit::log($saved, 'create', [], $saved->objData)
return $saved
static

model :: transaction ($callback)

line 147
Voert een database-transactie uit met de opgegeven callbackfunctie, waarbij wordt gegarandeerd dat alle bewerkingen binnen de transactie succesvol worden voltooid voordat deze wordt bevestigd.
static::DB()->transaction($callback)
static

model :: query:query

line 148
Voert een query uit op de database van het model en retourneert de resultaten op basis van de opgegeven voorwaarden.
phlo('query', class: static::class)
static

model :: column (...$args):array

line 150
Toegang tot een specifieke kolom van de records die door het model zijn geladen, met behulp van de fetchAll-methode met de FETCH_COLUMN-optie van PDO.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_COLUMN])
static

model :: item (...$args)

line 151
Laadt records uit de database met de opgegeven argumenten en fetch-modus, en retourneert een enkele kolom met gegevens.
static::recordsLoad($args, 'fetch', [\PDO::FETCH_COLUMN])
static

model :: pair (...$args):array

line 152
Laadt records uit de database als een sleutel-waarde paar array met de opgegeven fetch-modus.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_KEY_PAIR])
static

model :: records (...$args):array

line 153
Haal alle records op uit het model, en laad ze als instanties van de modelklasse.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_CLASS|\PDO::FETCH_UNIQUE, static::class], true)
static

model :: recordCount (...$args)

line 154
Geeft het totale aantal records in de database-tabel van het model terug.
static::item(...$args, columns: 'COUNT('.static::idColumn().')')
static

model :: record (...$args):?static

line 155
Haal een enkel record op uit de records van het model op basis van de opgegeven argumenten, en retourneer een fout als er meerdere records worden gevonden.
count($records = static::records(...$args)) > 1 ? error('Multiple records for '.static::class) : (current($records) ?: null)
static

model :: recordsLoad ($args, $fetch, $fetchMode, $saveRelations = false)

line 162
Loads records and keeps a full record read on the request-local state for relation reuse.
$pk = static::idColumn()
$args['table'] ??= static::$table
$saveRelations && $args['columns'] ??= static::$table.'.'.$pk.' as _,'.static::columns()
isset(static::$joins) && debug && error('DEPRECATED: static $joins in '.static::class.'. Use getParent/getChildren/getMany instead.')
isset(static::$joins) && $args['joins'] = static::$joins.(isset($args['joins']) ? " $args[joins]" : void)
method_exists(static::class, 'where') && $args['where'] = static::where().(isset($args['where']) ? " AND $args[where]" : void)
isset(static::$group) && $args['group'] ??= static::$group
isset(static::$order) && $args['order'] ??= static::$order
if ($cacheKey = $args['cacheKey'] ?? null) unset($args['cacheKey'])
if ($duration = $args['cache'] ?? static::objCache()){
	unset($args['cache'])
	$cacheArgs = $args
	ksort($cacheArgs)
	$records = apcu($cacheKey ?? static::class.slash.md5(json_encode($cacheArgs)), fn() => static::DB()->load(...$args)->$fetch(...$fetchMode), $duration === true ? 86400 : $duration)
}
else $records = static::DB()->load(...$args)->$fetch(...$fetchMode)
if ($saveRelations && $records){
	$state = static::state()
	$state->records[static::class] = array_replace($state->records[static::class] ?? [], array_column($records, null, $pk))
	count($state->records[static::class]) > static::objRecordLimit() && $state->records[static::class] = array_slice($state->records[static::class], -static::objRecordLimit(), preserve_keys: true)
}
return $records
static

model :: objRel ($key):array

line 187
Toegang tot het relatie-object dat in het model is gedefinieerd, en retourneert metadata of roept een methode aan als deze bestaat.
$state = static::state()
return $state->meta[static::class][$key] ??= method_exists(static::class, $key) ? static::$key() : static::$$key ?? []
prop

%model -> objState:array

line 192
De `$objState`-eigenschap van het model bevat de staat van het object, inclusief zijn ouders, kinderen en veel-relaties, geïnitieerd als lege arrays.
['parents' => [], 'children' => [], 'many' => []]
method

%model -> objGet ($key)

line 193
Haal een object op dat is gekoppeld aan de opgegeven sleutel vanuit de ouder-, kind- of vele relaties in het model.
$this->getParent($key) ?? $this->getChildren($key) ?? $this->getMany($key)
method

%model -> objIn ($ids, $db = null):string

line 194
Geeft een geciteerde lijst van ID's uit de database of 'NULL' als er geen ID's zijn opgegeven.
$ids ? ($db ?? static::DB())->quoteList($ids) : 'NULL'
method

%model -> objMirror (string $bucket, $key)

line 200
Mirrors a freshly loaded relation onto a stale reference to the same record.
$pk = $this->objData[static::idColumn()] ?? null
if ($pk === null) return
$canonical = static::state()->records[static::class][$pk] ?? null
if (!$canonical || $canonical === $this) return
if (array_key_exists($key, $this->objState[$bucket] ?? [])) return
if (array_key_exists($key, $canonical->objState[$bucket] ?? [])) $this->objState[$bucket][$key] = $canonical->objState[$bucket][$key]
method

%model -> getParent ($key)

line 209
Haal het bovenliggende object op dat is gekoppeld aan een gegeven sleutel uit de status van het model, en laad het indien nodig.
if (array_key_exists($key, $this->objState['parents'])) return $this->objState['parents'][$key]
$state = static::state()
$parents = self::objRel('objParents')
if (!$relation = $parents[$key] ?? null) return
$isArray = is_array($relation)
$class = $isArray ? $relation['obj'] : $relation
$column = $isArray ? $relation['key'] ?? $key : $key
if (!$parentId = $this->objData[$column] ?? null) return $this->objState['parents'][$key] = null
if (!isset($state->records[$class][$parentId])){
	$idsToLoad = [$parentId => true]
	$allObjData = array_map(fn($record) => $record->objData, $state->records[static::class] ?? [])
	foreach ($parents as $pKey => $pRelation){
		$pIsArray = is_array($pRelation)
		$pClass = $pIsArray ? $pRelation['obj'] : $pRelation
		if ($pClass === $class) foreach (array_column($allObjData, $pIsArray ? $pRelation['key'] ?? $pKey : $pKey) as $pId) $pId && !isset($state->records[$class][$pId]) && $idsToLoad[$pId] = true
	}
	if ($idsToLoad = array_keys($idsToLoad)) $class::records(where: $class::idColumn().' IN ('.$this->objIn($idsToLoad, $class::DB()).')')
}
$parentObject = $state->records[$class][$parentId] ?? null
return $this->objState['parents'][$key] = $parentObject
method

%model -> getChildren ($key)

line 232
Haal de kindobjecten op die zijn gekoppeld aan een bepaalde sleutel uit de status van het model, en laad ze indien nodig.
if (array_key_exists($key, $this->objState['children'])) return $this->objState['children'][$key]
$state = static::state()
if (!$relation = self::objRel('objChildren')[$key] ?? null) return
$isArray = is_array($relation)
$class = $isArray ? $relation['obj'] : $relation
$column = $isArray ? $relation['key'] : static::objShortName()
$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['children']))
if ($toLoad){
	$fq = $class::DB()->fieldQuotes
	$children = $class::records(where: $fq.$column.$fq.' IN ('.$this->objIn(array_keys($toLoad), $class::DB()).')')
	foreach ($toLoad AS $parentRecord) $parentRecord->objState['children'][$key] = []
	foreach ($children AS $childId => $child) !is_null($pId = $child->objData[$column] ?? null) && isset($state->records[static::class][$pId]) && $state->records[static::class][$pId]->objState['children'][$key][$childId] = $child
}
$this->objMirror('children', $key)
return $this->objState['children'][$key] ?? []
method

%model -> getMany ($key)

line 250
Haal meerdere gerelateerde records op op basis van een opgegeven sleutel uit de status van het model, en laad ze indien ze nog niet aanwezig zijn.
if (array_key_exists($key, $this->objState['many'])) return $this->objState['many'][$key]
$state = static::state()
if (!$relation = self::objRel('objMany')[$key] ?? null) return
$class = $relation['obj']
$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['many']))
if ($toLoad){
	$fq = static::DB()->fieldQuotes
	$lk = $relation['localKey']
	$fk = $relation['foreignKey']
	$pivotRows = static::DB()->rows(table: $relation['table'], columns: $fq.$lk.$fq.comma.$fq.$fk.$fq, where: $fq.$lk.$fq.' IN ('.$this->objIn(array_keys($toLoad)).')')
	$targetIds = array_unique(array_map(fn($row) => $row->{$relation['foreignKey']}, $pivotRows ?: []))
	$targetRecords = $targetIds ? $class::records(where: $class::idColumn().' IN ('.$this->objIn($targetIds, $class::DB()).')') : []
	foreach ($toLoad AS $parentRecord) $parentRecord->objState['many'][$key] = []
	foreach ($pivotRows ?: [] AS $row){
		$parentId = $row->$lk
		$foreignId = $row->$fk
		if (isset($state->records[static::class][$parentId]) && isset($targetRecords[$foreignId])) $state->records[static::class][$parentId]->objState['many'][$key][$foreignId] = $targetRecords[$foreignId]
	}
}
$this->objMirror('many', $key)
return $this->objState['many'][$key] ?? []
method

%model -> getCount ($key):int

line 274
Haal het aantal gerelateerde records op voor een gegeven sleutel, waarbij indien nodig gegevens uit de database worden geladen en het resultaat in de status van het object wordt gecached.
if (array_key_exists($key, $this->objState['counts'] ?? [])) return $this->objState['counts'][$key]
$state = static::state()
if ($relation = self::objRel('objChildren')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['counts'] ?? []))
	if ($toLoad){
		$isArray = is_array($relation)
		$class = $isArray ? $relation['obj'] : $relation
		$column = $isArray ? $relation['key'] : static::objShortName()
		$fq = $class::DB()->fieldQuotes
		$counts = $class::pair(columns: $fq.$column.$fq.', COUNT(*)', where: $fq.$column.$fq.' IN ('.$this->objIn(array_keys($toLoad), $class::DB()).')', group: $fq.$column.$fq)
		foreach ($toLoad as $id => $record) $record->objState['counts'][$key] = (int)($counts[$id] ?? 0)
	}
	$this->objMirror('counts', $key)
	return $this->objState['counts'][$key] ?? 0
}
if ($relation = self::objRel('objMany')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['counts'] ?? []))
	if ($toLoad){
		$fq = static::DB()->fieldQuotes
		$localKey = $relation['localKey']
		$counts = static::DB()->load(table: $relation['table'], columns: $fq.$localKey.$fq.',COUNT(*)', where: $fq.$localKey.$fq.' IN ('.$this->objIn(array_keys($toLoad)).')', group: $fq.$localKey.$fq)->fetchAll(\PDO::FETCH_KEY_PAIR)
		foreach ($toLoad as $id => $record) $record->objState['counts'][$key] = (int)($counts[$id] ?? 0)
	}
	$this->objMirror('counts', $key)
	return $this->objState['counts'][$key] ?? 0
}
return 0
method

%model -> getLast ($key)

line 304
Haal het laatste kindobject op dat is gekoppeld aan de opgegeven sleutel uit de status van het model, en laad het indien nodig.
if (array_key_exists($key, $this->objState['last_child'] ?? [])) return $this->objState['last_child'][$key]
$state = static::state()
if ($relation = self::objRel('objChildren')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['last_child'] ?? []))
	if ($toLoad){
		$isArray = is_array($relation)
		$class = $isArray ? $relation['obj'] : $relation
		$column = $isArray ? $relation['key'] : static::objShortName()
		$childTable = $class::$table
		$fq = $class::DB()->fieldQuotes
		$qt = $fq.$childTable.$fq
		$qc = $fq.$column.$fq
		$ids = $this->objIn(array_keys($toLoad), $class::DB())
		$childPk = $class::idColumn()
		$joins = ' INNER JOIN (SELECT MAX('.$fq.$childPk.$fq.') AS last_id, '.$qc.' AS parent_id FROM '.$qt.' WHERE '.$qc.' IN ('.$ids.') GROUP BY '.$qc.') AS lcmax ON '.$qt.'.'.$fq.$childPk.$fq.' = lcmax.last_id'
		$lastChildren = $class::records(joins: $joins)
		foreach ($toLoad as $record) $record->objState['last_child'][$key] = null
		foreach ($lastChildren as $child) if (isset($state->records[static::class][$parentId = $child->objData[$column]])) $state->records[static::class][$parentId]->objState['last_child'][$key] = $child
	}
	$this->objMirror('last_child', $key)
	return $this->objState['last_child'][$key] ?? null
}
return null
static

model :: objResolveClass ($name):string

line 330
Lost de klassenaam op voor het opgegeven modelobject, waardoor dynamische klasseverwerking in Phlo mogelijk is.
$name
static

model :: objShortName ($class = null):string

line 331
Deze expressie haalt de naam van de huidige modelklasse op of de opgegeven klasse als deze bestaat, met gebruik van de statische context.
$class ?? static::class
static

model :: objParents:array

line 333
Geeft de ouderobjecten terug die zijn gekoppeld aan het huidige model, met gebruik van het gedefinieerde schema en het filteren van velden van het type 'parent'.
if (property_exists(static::class, 'objParents')) return static::$objParents
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'parent'), fn($f, $c) => $f->key ? arr(obj: static::objResolveClass($f->obj), key: $f->key) : (static::objResolveClass($f->obj ?? $c)))
static

model :: objChildren:array

line 339
Geeft de kindobjecten terug die zijn gekoppeld aan het huidige model, waarbij het gedefinieerde schema wordt gebruikt en velden van het type 'child' worden gefilterd.
if (property_exists(static::class, 'objChildren')) return static::$objChildren
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'child'), fn($f, $c) => $f->key ? arr(obj: static::objResolveClass($f->obj), key: $f->key) : (static::objResolveClass($f->obj ?? $c)))
static

model :: objMany:array

line 345
Geeft de 'objMany'-eigenschap terug als deze bestaat; anders wordt een array van gerelateerde objecten op basis van de schema-definitie opgehaald.
if (property_exists(static::class, 'objMany')) return static::$objMany
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'many'), fn($f) => arr(obj: static::objResolveClass($f->obj), table: $f->table, localKey: $f->localKey ?? static::objShortName(), foreignKey: $f->foreignKey ?? $f->obj))
object

%MySQL

/phlo/resources/DB/MySQL.phlo

MySQL handler via DB class

Reads host, database, user and password from the mysql section of %creds. It is the default assumption of the ORM, so a model that names no engine of its own ends up here.

mysqlpdodatabasesql
prop

%MySQL -> PDO:\PDO

line 12
Maakt een nieuwe PDO-instantie aan voor het verbinden met een MySQL-database met behulp van de opgegeven referenties.
new \PDO('mysql:host='.%creds->mysql->host.';dbname='.%creds->mysql->database, %creds->mysql->user, %creds->mysql->password)
object

%PostgreSQL

/phlo/resources/DB/PostgreSQL.phlo

PostgreSQL resource

Quotes identifiers with double quotes rather than backticks and has no INSERT IGNORE, so a duplicate is skipped with ON CONFLICT DO NOTHING. Postgres folds an unquoted name to lower case, so a column called createdAt in a schema is not the same one you get back unquoted.

postgresqlpdodatabasesql
prop

%PostgreSQL -> PDO:\PDO

line 12
Maakt een nieuwe PDO-instantie aan voor het verbinden met een PostgreSQL-database met de opgegeven inloggegevens.
new PDO('pgsql:host='.%creds->postgresql->host.';dbname='.%creds->postgresql->database, %creds->postgresql->user, %creds->postgresql->password)
prop

%PostgreSQL -> fieldQuotes:string

line 13
Geeft de veldnaam terug, omgeven door dubbele aanhalingstekens voor PostgreSQL-compatibiliteit.
dq
prop

%PostgreSQL -> insertIgnore:string

line 14
Voegt een nieuw record toe aan een PostgreSQL-database en negeert de bewerking als er al een record met dezelfde unieke sleutel bestaat.
void
prop

%PostgreSQL -> insertOnConflict:string

line 15
Voegt een nieuw record toe aan een PostgreSQL-database, en als er een conflict optreedt (bijv. een duplicaat sleutel), doet het niets in plaats van een fout te genereren.
' ON CONFLICT DO NOTHING'
method

%PostgreSQL -> lastId

line 21
Asks for the last id inside a savepoint, so a failed lastval() cannot abort the transaction.
$savepoint = $this->PDO->inTransaction()
$savepoint && $this->PDO->exec('SAVEPOINT phlo_lastid')
try {
	$id = $this->PDO->lastInsertId()
} catch (\Throwable $e){
	$id = false
}
if ($savepoint) $this->PDO->exec($id === false ? 'ROLLBACK TO SAVEPOINT phlo_lastid' : 'RELEASE SAVEPOINT phlo_lastid')
return $id
object

%Qdrant

/phlo/resources/DB/Qdrant.phlo

Embeddings resource with Qdrant

Embeddings are cached in APCu for four weeks per input, so repeating a search costs nothing at the AI end. create() opens a collection at 1536 dimensions, the length of an OpenAI vector, so state the size yourself when another engine fills it. search() without input sends a zero vector, which lists a collection rather than searching it.

qdrantembeddingsvectorsearchai
method

%Qdrant -> get (string $input, ?string $model = null):array

line 11
Haal een embedding op voor de gegeven invoerstring met behulp van het opgegeven model, en cache het resultaat gedurende 28 dagen.
apcu('embedding/'.token(input: $input), fn($input) => %AI->embedding(input: $input, model: $model), 86400 * 28)
method

%Qdrant -> collections:array

line 13
Haal een array van collectie namen op uit de Qdrant API-respons.
array_column($this->request('collections')->result->collections, 'name')
method

%Qdrant -> create ($collection, $size = 1536, $distance = 'Cosine'):bool

line 14
Maakt een nieuwe collectie aan in Qdrant met de opgegeven vectorgrootte en afstandsmetrieken.
$this->request("collections/$collection", PUT: arr(vectors: arr(size: $size, distance: $distance)))->status === 'ok'
method

%Qdrant -> upsert ($collection, $id, $input, ...$payload)

line 15
Deze functie werkt een punt bij of voegt een punt toe in een opgegeven Qdrant-collectie met behulp van de opgegeven ID en invoervector, samen met optionele payloadgegevens.
$this->request("collections/$collection/points", PUT: arr(points: [arr(id: $id, vector: $this->get($input), payload: $payload ?: null)]))->result->operation_id
method

%Qdrant -> delete ($collection, ...$ids)

line 16
Verwijdert opgegeven punten uit een Qdrant-collectie op basis van hun ID's.
$this->request("collections/$collection/points/delete", POST: arr(points: $ids))->result
method

%Qdrant -> search ($collection, $input = null, $top = 100):array

line 17
Zoekt naar punten in de opgegeven Qdrant-collectie op basis van de invoervector en retourneert de beste resultaten.
create($this->request("collections/$collection/points/search", POST: arr(vector: is_null($input) ? array_fill(0, 1536, 0) : $this->get($input), top: $top, with_payload: true))->result, fn($record) => $record->id, fn($record) => last($record = array_merge(get_object_vars($record), get_object_vars($record->payload)), obj(...array_filter($record, fn($key) => $key !== 'payload', ARRAY_FILTER_USE_KEY))))
method

%Qdrant -> drop ($collection)

line 18
Verwijdert de opgegeven collectie uit Qdrant door een DELETE-verzoek naar de juiste endpoint te sturen.
$this->request("collections/$collection", DELETE: true)->result
method

%Qdrant -> request ($uri, ...$data)

line 20
Verzendt een HTTP-verzoek naar de opgegeven Qdrant-server-URI met optionele gegevens en retourneert de gedecodeerde JSON-reactie.
json_decode(HTTP(%creds->qdrant->server.$uri, %creds->qdrant->key ? ['api-key: '.%creds->qdrant->key] : [], true, ...$data))
object

%query

/phlo/resources/DB/query.phlo

Fluent query builder for Phlo ORM

For everything named arguments cannot say: eq, gt, like, in, isNull, order, limit and offset, chained and closed with records, record, column, item or count. Column names are quoted for the driver you are on, so the same chain works on MySQL and Postgres. Values go in as bindings, so a search box can be passed straight through.

querybuilderormdatabasesql
prop

%query -> class

line 11
Haal het type van de huidige query-object op.
prop

%query -> conditions

line 12
Definieert voorwaarden voor het filteren van resultaten in een query.
[]
prop

%query -> bindings

line 13
De `query->$bindings` haalt de bindings op die aan een query zijn gekoppeld in Phlo, waardoor toegang wordt verkregen tot de parameters die zijn gebruikt bij de uitvoering van de query.
[]
prop

%query -> orderBy

line 14
Geeft het veld op waarop de resultaten van een query moeten worden gesorteerd.
prop

%query -> limitVal

line 15
Stelt het maximale aantal resultaten in dat uit een query in Phlo moet worden geretourneerd.
prop

%query -> offsetVal

line 16
Haal de huidige offsetwaarde op voor paginering in een query.
method

%query -> fq:string

line 17
Deze expressie haalt de veldquotes op uit de databaseklasse die aan de huidige instantie is gekoppeld, of valt terug op 'bt' als de klasse niet is ingesteld.
($class = $this->class) ? $class::DB()->fieldQuotes : bt
method

%query -> q ($column):string

line 18
Valideert de opgegeven kolomnaam voor de query builder en formatteert deze door elk deel te omringen met de volledig gekwalificeerde naam.
preg_match('/^[A-Za-z_][A-Za-z0-9_.]*$/', $column) || error("Invalid column for query builder: $column")
$fq = $this->fq
return implode(dot, array_map(fn($part) => $fq.$part.$fq, explode(dot, $column)))
method

%query -> eq ($column, $value):static

line 24
Filtert de queryresultaten om alleen diegene op te nemen waar de opgegeven kolom gelijk is aan de gegeven waarde.
$this->where($this->q($column)." = ?", $value)
method

%query -> neq ($column, $value):static

line 25
Filtert resultaten waarbij de opgegeven kolom niet gelijk is aan de gegeven waarde.
$this->where($this->q($column)." != ?", $value)
method

%query -> gt ($column, $value):static

line 26
Voegt een voorwaarde toe aan de query die resultaten filtert waarbij de opgegeven kolom groter is dan de gegeven waarde.
$this->where($this->q($column)." > ?", $value)
method

%query -> gte ($column, $value):static

line 27
Genereert een queryvoorwaarde die controleert of de waarde van de opgegeven kolom groter dan of gelijk is aan een gegeven waarde.
$this->where($this->q($column)." >= ?", $value)
method

%query -> lt ($column, $value):static

line 28
Voegt een voorwaarde toe aan de query om resultaten te filteren waarbij de opgegeven kolom kleiner is dan de gegeven waarde.
$this->where($this->q($column)." < ?", $value)
method

%query -> lte ($column, $value):static

line 29
Voegt een voorwaarde toe aan de query die resultaten filtert waarbij de opgegeven kolom kleiner dan of gelijk is aan de gegeven waarde.
$this->where($this->q($column)." <= ?", $value)
method

%query -> like ($column, $value):static

line 30
Voegt een voorwaarde toe aan de query die controleert of de opgegeven kolom een waarde bevat die lijkt op de opgegeven waarde met behulp van de SQL LIKE-operator.
$this->where($this->q($column)." LIKE ?", $value)
method

%query -> in ($column, array $values):static

line 31
Voegt een voorwaarde toe aan de query om resultaten te filteren waarbij de waarde van de opgegeven kolom in de opgegeven array van waarden staat.
$this->where($this->q($column)." IN (".implode(comma, array_fill(0, count($values), qm)).")", ...$values)
method

%query -> isNull ($column):static

line 32
Controleert of de opgegeven kolom in de query null is.
$this->where($this->q($column)." IS NULL")
method

%query -> notNull ($column):static

line 33
Voegt een voorwaarde toe aan de query om ervoor te zorgen dat de opgegeven kolom niet null is.
$this->where($this->q($column)." IS NOT NULL")
method

%query -> between ($column, $min, $max):static

line 34
Filtert resultaten om alleen diegene op te nemen waarbij de waarde van de opgegeven kolom tussen de gegeven minimum- en maximumwaarden ligt.
$this->where($this->q($column)." BETWEEN ? AND ?", $min, $max)
method

%query -> raw ($sql, ...$bindings):static

line 35
Voert een ruwe SQL-query uit met de opgegeven bindings, waardoor dynamische queryconstructie mogelijk is.
$this->where($sql, ...$bindings)
method

%query -> where ($condition, ...$values):static

line 36
Voegt een voorwaarde toe aan de query met de opgegeven waarden voor binding. Het maakt dynamische filtering van resultaten mogelijk op basis van de opgegeven voorwaarde.
$this->conditions[] = $condition
foreach ($values AS $v) $this->bindings[] = $v
return $this
method

%query -> order ($order):static

line 42
Stelt de volgorde voor de query in met de opgegeven $order-waarde en retourneert de huidige instantie.
$this->orderBy = $order
return $this
method

%query -> limit ($limit):static

line 47
Stelt het maximum aantal resultaten in dat uit een query moet worden geretourneerd, gedefinieerd door de $limit parameter.
$this->limitVal = $limit
return $this
method

%query -> offset ($offset):static

line 52
Stelt de offsetwaarde voor de query in, waardoor paginering van resultaten mogelijk is.
$this->offsetVal = $offset
return $this
method

%query -> build:array

line 56
Bouwt een argumentarray voor een query op basis van opgegeven voorwaarden, volgorde, limiet en bindingen voor gebruik in databasebewerkingen.
$where = $this->conditions ? implode(' AND ', $this->conditions) : void
$limit = $this->limitVal ? ($this->offsetVal ? "$this->offsetVal,$this->limitVal" : "$this->limitVal") : void
$args = ['where' => $where ?: void, 'order' => $this->orderBy ?: void, 'limit' => $limit ?: void]
foreach ($this->bindings AS $b) $args[] = $b
return $args
prop

%query -> records:array

line 64
Haal een verzameling records op uit de opgegeven klasse met behulp van de verstrekte bouwparameters.
($class = $this->class) && $class::records(...$this->build)
prop

%query -> record:?model

line 65
Haal een record op uit de opgegeven klasse met behulp van de verstrekte bouwparameters.
($class = $this->class) && $class::record(...$this->build)
prop

%query -> column:array

line 66
Toegang tot een specifieke kolom van een queryresultaatset met behulp van de gedefinieerde klasse en buildparameters.
($class = $this->class) && $class::column(...$this->build)
prop

%query -> item

line 67
Haal een item op uit een klasse met behulp van de opgegeven bouwparameters.
($class = $this->class) && $class::item(...$this->build)
prop

%query -> count

line 68
Geeft het totale aantal records in de opgegeven klasse terug met behulp van de recordCount-methode.
($class = $this->class) && $class::recordCount(...$this->build)
method

%query -> delete:int

line 69
Verwijdert records uit de database op basis van opgegeven voorwaarden. Als er geen voorwaarden zijn opgegeven, wordt er een foutmelding weergegeven.
$class = $this->class
$where = $this->conditions ? implode(' AND ', $this->conditions) : error('Cannot delete without conditions')
return $class::delete($where, ...$this->bindings)
object

%SQLite

/phlo/resources/DB/SQLite.phlo

SQLite resource

One file, one database, given as a path: %SQLite('/path/db.sqlite'). It writes with a lock over the whole file, so it fits a single site or a worker but not a set of processes writing at once. Perfect where you want the ORM without a server.

sqlitepdodatabasesql
static

SQLite :: __handle

line 12
Deze eigenschap bevat de handle naar de SQLite-databaseverbinding, waarmee interactie met de database mogelijk is.
"SQLite/$file"
method

%SQLite -> __construct (private string $file)

line 13
Initialiseert een nieuwe SQLite-instantie met het opgegeven databasebestand.
prop

%SQLite -> PDO:\PDO

line 14
Maakt een nieuwe PDO-instantie voor SQLite met het opgegeven bestand.
new PDO('sqlite:'.$this->file)
prop

%SQLite -> insertIgnore:string

line 15
Voegt een nieuw record toe aan de SQLite-database, waarbij de bewerking wordt genegeerd als er al een record met dezelfde primaire sleutel bestaat.
' OR IGNORE'

Laatst bijgewerkt op 23-08-2026

We gebruiken essentiële cookies om deze site te laten werken. Met uw toestemming gebruiken we ook analytics om de site te verbeteren.