forked from AppStateESS/InternshipInventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseStorage.php
95 lines (73 loc) · 2.09 KB
/
DatabaseStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Intern;
/**
* Class to handle saving and loading objects from the database.
*
* @author jbooker
* @package intern
*/
class DatabaseStorage {
/**
* Saves the given object to the database.
* @param Object $obj
*/
public static function save(DbStorable $obj)
{
$db = new \PHPWS_DB($obj->getTableName());
try {
$result = $db->saveObject($obj);
} catch (\Exception $e) {
// rethrow any exceptions
throw $e;
}
if (\PHPWS_Error::logIfError($result)) {
throw new \Exception($result->toString());
}
return $obj->id;
}
/**
* Loads an object from the database using the given class name and object id.
*
* @param String $class
* @param int $id
*/
public static function load($class, $id)
{
\PHPWS_Core::initModClass($class . '.php');
$table = $class::getTableName();
$db = new \PHPWS_DB($table);
$instance = new $class;
$db->addWhere('id', $id);
$result = $db->loadObject($instance);
if (\PHPWS_Error::logIfError($result)) {
throw new \Exception($result->toString());
}
return $result;
}
public static function saveObject(DbStorable $o)
{
$vars = $o->extractVars();
$tableName = $o::getTableName();
// Check if the key already exists
$query = "SELECT * FROM $tableName WHERE id = {$vars['id']}";
$result = \PHPWS_DB::getAll($query);
if (count($result) > 0) {
$exists = true;
} else {
$exists = false;
}
$db = new \PHPWS_DB($o->getTableName());
foreach ($vars as $key => $value) {
$db->addValue($key, $value);
}
if ($exists) {
$db->addWhere('id', $vars['id']);
$result = $db->update();
} else {
$result = $db->insert(false);
}
if(\PHPWS_Error::logIfError($result)) {
throw new \Exception($result->toString());
}
}
}