
12.02.2009, 18:02
|
|
Новичок
Регистрация: 11.02.2009
Сообщений: 21
Провел на форуме: 36983
Репутация:
0
|
|
PHP код:
<?php
require_once(dirname(__FILE__) . '/DB.php');
class DBObject
{
public $table = '';
private $id = null;
public function __construct()
{
return $this;
}
public static function create()
{
return new self();
}
public static function getById($groupId)
{
$new = new self();
$new->loadById($groupId);
return $new;
}
public function loadById($groupId)
{
$query = 'SELECT * FROM ' . $this->table . ' WHERE id = ' . $groupId;
$result = DB::selectQuery($query);
if ($result->count == 0)
return false;
$row = $result->fetchRow();
$this->makeObject($row);
return $this;
}
public function makeObject($array = array())
{
$this->id = $array['id'];
return $this;
}
public function getId()
{
return $this->id;
}
protected function makeArray()
{
return array(
'id' => $this->getId()
);
}
public function delete()
{
if (!$this->getId())
return $this;
$query = 'DELETE FROM ' . $this->table . ' WHERE id = ' . $this->getId();
DB::execQuery($query);
return $this;
}
public function save()
{
if ($this->getId()) {
return $this->update();
} else {
return $this->add();
}
}
public function update()
{
$arr = $this->makeArray();
unset($arr['id']);
$query = 'UPDATE ' . $this->table . ' SET ';
$i = 0;
foreach($arr as $key => $value) {
$i++;
if ($i > 1) {
$query .= ', ';
}
$query .= $key . ' = "' . $value . '"';
}
$query .= 'WHERE id = ' . $this->getId();
DB::execQuery($query);
return $this;
}
public function add()
{
$arr = $this->makeArray();
if (isset($arr['id'])) {
unset($arr['id']);
}
$query = 'INSERT INTO ' . $this->table . ' (' . implode(', ', array_keys($arr)) . ')';
$query .= 'VALUES (';
$i = 0;
foreach($arr as $value) {
$i++;
if ($i > 1) {
$query .= ', ';
}
$query .= '"' . $value . '"';
}
$query .= ')';
$this->id = DB::insertQuery($query);
Вот он
|
|
|