Add abstract base class for database tables
authorJoey Schulze <joey@infodrom.org>
Fri, 4 Apr 2014 19:04:48 +0000 (19:04 +0000)
committerJoey Schulze <joey@infodrom.org>
Fri, 4 Apr 2014 19:04:48 +0000 (19:04 +0000)
class/databasetable.class.php [new file with mode: 0644]

diff --git a/class/databasetable.class.php b/class/databasetable.class.php
new file mode 100644 (file)
index 0000000..cc52642
--- /dev/null
@@ -0,0 +1,81 @@
+<?php
+
+abstract class DatabaseTable {
+  protected $idcolumn = 'id';
+  protected $db;
+  protected $table;
+  protected $data;
+  protected $id;
+
+  public function __construct($table, $id=false, $column_or_db=false, $column=false)
+  {
+    global $db;
+
+    $this->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