web-base/core/Objects/DatabaseEntity/DatabaseEntity.class.php

73 lines
1.7 KiB
PHP
Raw Normal View History

2022-06-17 20:53:35 +02:00
<?php
namespace Objects\DatabaseEntity;
use Driver\SQL\Condition\Condition;
use Driver\SQL\SQL;
abstract class DatabaseEntity {
private static array $handlers = [];
private ?int $id;
public function __construct() {
$this->id = null;
}
public static function find(SQL $sql, int $id): ?DatabaseEntity {
$handler = self::getHandler($sql);
return $handler->fetchOne($id);
2022-06-17 20:53:35 +02:00
}
public static function findAll(SQL $sql, ?Condition $condition): ?array {
$handler = self::getHandler($sql);
return $handler->fetchMultiple($condition);
2022-06-17 20:53:35 +02:00
}
public function save(SQL $sql): bool {
$handler = self::getHandler($sql);
$res = $handler->insertOrUpdate($this);
2022-06-17 20:53:35 +02:00
if ($res === false) {
return false;
} else if ($this->id === null) {
$this->id = $res;
}
return true;
}
public function delete(SQL $sql): bool {
$handler = self::getHandler($sql);
2022-06-17 20:53:35 +02:00
if ($this->id === null) {
$handler->getLogger()->error("Cannot delete entity without id");
2022-06-17 20:53:35 +02:00
return false;
}
return $handler->delete($this->id);
2022-06-17 20:53:35 +02:00
}
public static function getHandler(SQL $sql, $obj_or_class = null): DatabaseEntityHandler {
2022-06-17 20:53:35 +02:00
if (!$obj_or_class) {
$obj_or_class = get_called_class();
}
if (!($obj_or_class instanceof \ReflectionClass)) {
$class = new \ReflectionClass($obj_or_class);
} else {
$class = $obj_or_class;
}
$handler = self::$handlers[$class->getShortName()] ?? null;
if (!$handler) {
$handler = new DatabaseEntityHandler($sql, $class);
2022-06-17 20:53:35 +02:00
self::$handlers[$class->getShortName()] = $handler;
}
return $handler;
}
public function getId(): ?int {
return $this->id;
}
}