<?php
namespace Tlf\BigDb;
/**
* Load ORMs
*/
trait GetOrms {
/**
* Get an array of BigOrm instances from the given database table. Will map table to the correct ORM class
*
* @param $table the database table to query
* @param $where array<string, mixed> array of WHERE conditions to refine the query
*
* @return array<int, BigOrm> array of BigOrm instances (generally subclasses)
*/
public function get(string $table, array $where = []): array{
$rows = $this->select($table, $where);
$orms = [];
foreach ($rows as $row){
$orms[] = $this->row_to_orm($table, $row);
}
return $orms;
}
/**
* Execute a stored query, and get an array of orm objects from the results
*
* @param $table the database table
* @param $which_query the key within the table's sql file. Uses `$table.$which_query ?? `$which_query`.
* @param $binds array<string, mixed> EXPERIMENTAL key/value array to bind to the stored query. Uses pdo_quote & str_replace NOT the built-in `pdo->bind()`
*
* @return array<int, \Tlf\BigOrm> array of BigOrm instances, with key being numeric index.
*/
public function query(string $table, string $which_query, array $binds = []): array {
$this->init_sql();
$key = "{$table}.{$which_query}";
if (!isset($this->sql[$key]))$key = $which_query;
$rows = $this->query_rows($key, $binds);
$orms = [];
foreach ($rows as $row){
$orms[] = $this->row_to_orm($table, $row);
}
return $orms;
}
/**
* Get an ORM for the given table row.
*
* @param $table the database table the row was loaded from
* @param $row the the row to convert to ORM
* @return BigOrm
*/
public function row_to_orm(string $table, array $row): \Tlf\BigOrm {
$class = $this->get_orm_class($table);
$orm = new $class($this);
$orm->set_from_db($row);
return $orm;
}
/**
* Get the BigOrm (sub)class for the given table
*
* @param $table
* @return string fully qualified class name
*
* @override for a custom orm class loader
*/
public function get_orm_class(string $table): string {
$class = ucfirst($table);
$fqn = $this->get_orm_namespace().'\\'.$class;
return $fqn;
}
/**
* Get the namespace that all the orm classes are directly under. By default, uses `$this->orm_namespace`
*
* @override required if you do set `$bigDb->orm_namespace = 'Some\\Namespace'`
*/
public function get_orm_namespace(): string{
return $this->orm_namespace;
}
}