5 use Friendica\Database\Database;
6 use Friendica\Network\HTTPException;
7 use Psr\Log\LoggerInterface;
12 * The Model classes inheriting from this abstract class are meant to represent a single database record.
13 * The associated table name has to be provided in the child class, and the table is expected to have a unique `id` field.
17 abstract class BaseModel
19 protected static $table_name;
23 /** @var LoggerInterface */
27 * Model record abstraction.
28 * Child classes never have to interact directly with it.
29 * Please use the magic getter instead.
35 public function __construct(Database $dba, LoggerInterface $logger)
38 $this->logger = $logger;
42 * Magic getter. This allows to retrieve model fields with the following syntax:
43 * - $model->field (outside of class)
44 * - $this->field (inside of class)
48 * @throws HTTPException\InternalServerErrorException
50 public function __get($name)
52 if (empty($this->data['id'])) {
53 throw new HTTPException\InternalServerErrorException(static::class . ' record uninitialized');
56 if (!array_key_exists($name, $this->data)) {
57 throw new HTTPException\InternalServerErrorException('Field ' . $name . ' not found in ' . static::class);
60 return $this->data[$name];
64 * Fetches a single model record. The condition array is expected to contain a unique index (primary or otherwise).
68 * @param array $condition
70 * @throws HTTPException\NotFoundException
72 public function fetch(array $condition)
74 $intro = $this->dba->selectFirst(static::$table_name, [], $condition);
77 throw new HTTPException\NotFoundException(static::class . ' record not found.');
86 * Deletes the model record from the database.
87 * Prevents further methods from being called by wiping the internal model data.
89 public function delete()
91 if ($this->dba->delete(static::$table_name, ['id' => $this->id])) {