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
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;
57 * Performance-improved model creation in a loop
59 * @param BaseModel $prototype
63 public static function createFromPrototype(BaseModel $prototype, array $data)
65 $model = clone $prototype;
67 $model->originalData = $data;
73 * Magic isset method. Returns true if the field exists, either in the data prperty array or in any of the local properties.
74 * Used by array_column() on an array of objects.
79 public function __isset($name)
81 return in_array($name, array_merge(array_keys($this->data), array_keys(get_object_vars($this))));
85 * Magic getter. This allows to retrieve model fields with the following syntax:
86 * - $model->field (outside of class)
87 * - $this->field (inside of class)
91 * @throws HTTPException\InternalServerErrorException
93 public function __get($name)
97 if (!array_key_exists($name, $this->data)) {
98 throw new HTTPException\InternalServerErrorException('Field ' . $name . ' not found in ' . static::class);
101 return $this->data[$name];
105 * @param string $name
106 * @param mixed $value
108 public function __set($name, $value)
110 $this->data[$name] = $value;
113 public function toArray()
118 protected function checkValid()
120 if (empty($this->data['id'])) {
121 throw new HTTPException\InternalServerErrorException(static::class . ' record uninitialized');