This repository has been archived on 2024-10-04. You can view files and clone it, but cannot push or open issues or pull requests.
AroMVC/AroMVC/Model.php
2017-02-28 15:46:54 -06:00

82 lines
No EOL
2.2 KiB
PHP

<?php
namespace AroMVC\Core;
use AroMVC\Core\Database as db;
abstract class Model {
protected $rawData = [];
protected $associations = [];
protected $hooks = [];
protected static $table = null;
protected $index = "id";
protected $deleted = false;
protected $modified = [];
public function __construct() {}
public static function withId(int $id) {
$new = new static();
$new->initialize();
return $new;
}
public static function withRow(array $row) {
$new = new static();
$new->initialize();
array_walk($row, function($v, $k) use (&$new) {
$new->rawData[strtolower($k)] = $v;
});
return $new;
}
protected abstract function initialize();
protected function setTable(string $tableName) {
$this->table = $tableName;
}
protected function get(string $name) {
return $this->rawData[$name];
}
public function __get(string $name) {
$name = strtolower($name);
if(array_key_exists($name, $this->hooks))
return $this->hooks[$name]();
else if(array_key_exists($name, $this->associations))
return $this->rawData[$this->associations[$name]];
else if(array_key_exists($name, $this->rawData))
return $this->rawData[$name];
else return null;
}
public function __set(string $name, $value) {
$name = strtolower($name);
if(array_key_exists($name, $this->associations))
$rawData[$this->associations[$name]] = $value;
else if(array_key_exists($name, $this->rawData))
$rawData[$name] = $value;
else
throw new \Exception("Cannot set the value for property '$name'.");
}
protected function addHook(string $name, $func) {
$this->hooks[strtolower($name)] = $func;
}
protected function addAssociation(string $associationName, string $rawName) {
$this->associations[strtolower($associationName)] = strtolower($rawName);
}
public static function select(): Selectable {
return db::select("*", new static)->from(self::$table);
}
public function update() {
}
public function delete() {
}
}