From: Joey Schulze Date: Fri, 4 Apr 2014 19:04:48 +0000 (+0000) Subject: Add abstract base class for database tables X-Git-Url: https://git.infodrom.org/?p=infodrom.org%2Fservice.infodrom.org;a=commitdiff_plain;h=8e8be6a10d9ca53d87885ffe71a94c20a6ee0b36 Add abstract base class for database tables --- diff --git a/class/databasetable.class.php b/class/databasetable.class.php new file mode 100644 index 0000000..cc52642 --- /dev/null +++ b/class/databasetable.class.php @@ -0,0 +1,81 @@ +table = $table; + + if ($column_or_db && is_object($column_or_db)) { + $this->db = $column_or_db; + $col = $column; + } else { + $this->db = $db; + $col = $column_or_db; + } + + if ($id && !$col) $this->load($id); + if ($id && $col) $this->loadByColumn($id,$col); + } + + protected function postLoad() {} + + protected function load($id) + { + $sql = sprintf("SELECT * FROM %s WHERE %s = %d LIMIT 1", + $this->table, $this->idcolumn, $id); + $this->data = $this->db->fetchObject($sql); + if ($this->data) { + $idcolumn = $this->idcolumn; + $this->id = $this->data->$idcolumn; + $this->postLoad(); + return true; + } + return false; + } + + protected function loadByColumn($id,$column) + { + $sql = sprintf("SELECT * FROM %s WHERE `%s` = %s", + $this->table, $column, $this->db->quote($id)); + $this->data = $this->db->fetchObject($sql); + if ($this->data) { + $idcolumn = $this->idcolumn; + $this->id = $this->data->$idcolumn; + $this->postLoad(); + } + } + + public function id() + { + return $this->id; + } + + public function fetch() + { + return $this->data; + } + + public function modify($column, $value=false, $id=false) + { + if (!is_array($column) && $value !== false) + $column = array($column => $value); + elseif (!is_array($column) || $value !== false) + throw Exception('modify called with wrong parameters'); + + if ($this->db->update($this->table, $column, $this->idcolumn.'='.($id === false ? $this->id : $id))) + return $id === false ? $this->load($this->id) : true; + else + return false; + } + +} + +?> \ No newline at end of file