db = new \App\Core\Database($settings); if (empty($this->table)) { // Guess table name from class name (snake_case plural) $this->table = strtolower(preg_replace('/(?<=[a-z])[A-Z]/', '_$0', get_class($this))); $this->table = strtolower($this->table . 's'); } } /** * Find a record by primary key. * * @param mixed $id * @return static|null */ public function find($id) { $sql = "SELECT * FROM {$this->table} WHERE {$this->primaryKey} = ?"; $result = $this->db->first($sql, [$id]); if ($result) { $model = static::class; $instance = new $model($this->db->getConnection()); // We need to pass settings? We'll adjust. // Actually we need to pass settings to constructor. Let's change approach. // We'll instead return a plain array for simplicity, or we can create a new instance with settings. // For now, we'll return the raw data. return $result; } return null; } /** * Get all records. * * @return array */ public function all(): array { $sql = "SELECT * FROM {$this->table}"; return $this->db->select($sql); } /** * Insert a new record. * * @param array $data * @return int */ public function insert(array $data): int { return $this->db->insert($this->table, $data); } /** * Update record by primary key. * * @param mixed $id * @param array $data * @return int */ public function update($id, array $data): int { return $this->db->update($this->table, $data, "{$this->primaryKey} = ?", [$id]); } /** * Delete record by primary key. * * @param mixed $id * @return int */ public function delete($id): int { return $this->db->delete($this->table, "{$this->primaryKey} = ?", [$id]); } /** * Query builder: select. * * @param string $columns * @return $this */ // We can extend later. /** * Get database connection. */ protected function getDb(): \App\Core\Database { return $this->db; }}