5 use Friendica\Database\Database;
6 use Friendica\Network\HTTPException;
7 use Psr\Log\LoggerInterface;
10 * The Model classes inheriting from this abstract class are meant to represent a single database record.
11 * The associated table name has to be provided in the child class, and the table is expected to have a unique `id` field.
15 abstract class BaseModel extends BaseEntity
19 /** @var LoggerInterface */
23 * Model record abstraction.
24 * Child classes never have to interact directly with it.
25 * Please use the magic getter instead.
32 * Used to limit/avoid updates if no data was changed.
36 private $originalData = [];
39 * @param Database $dba
40 * @param LoggerInterface $logger
41 * @param array $data Table row attributes
43 public function __construct(Database $dba, LoggerInterface $logger, array $data = [])
46 $this->logger = $logger;
48 $this->originalData = $data;
51 public function getOriginalData()
53 return $this->originalData;
56 public function resetOriginalData()
58 $this->originalData = $this->data;
62 * Performance-improved model creation in a loop
64 * @param BaseModel $prototype
68 public static function createFromPrototype(BaseModel $prototype, array $data)
70 $model = clone $prototype;
72 $model->originalData = $data;
78 * Magic isset method. Returns true if the field exists, either in the data prperty array or in any of the local properties.
79 * Used by array_column() on an array of objects.
84 public function __isset($name)
86 return in_array($name, array_merge(array_keys($this->data), array_keys(get_object_vars($this))));
90 * Magic getter. This allows to retrieve model fields with the following syntax:
91 * - $model->field (outside of class)
92 * - $this->field (inside of class)
96 * @throws HTTPException\InternalServerErrorException
98 public function __get($name)
102 if (!array_key_exists($name, $this->data)) {
103 throw new HTTPException\InternalServerErrorException('Field ' . $name . ' not found in ' . static::class);
106 return $this->data[$name];
110 * @param string $name
111 * @param mixed $value
113 public function __set($name, $value)
115 $this->data[$name] = $value;
118 public function toArray()
123 protected function checkValid()
125 if (empty($this->data['id'])) {
126 throw new HTTPException\InternalServerErrorException(static::class . ' record uninitialized');