3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Provides an object interface to a table row
10 * LICENSE: This source file is subject to version 3.0 of the PHP license
11 * that is available through the world-wide-web at the following URI:
12 * http://www.php.net/license/3_0.txt. If you did not receive a copy of
13 * the PHP License and are unable to obtain it through the web, please
14 * send a note to license@php.net so we can mail you a copy immediately.
18 * @author Stig Bakken <stig@php.net>
19 * @copyright 1997-2007 The PHP Group
20 * @license http://www.php.net/license/3_0.txt PHP License 3.0
22 * @link http://pear.php.net/package/DB
26 * Obtain the DB class so it can be extended from
28 require_once 'DB.php';
31 * Provides an object interface to a table row
33 * It lets you add, delete and change rows using objects rather than SQL
38 * @author Stig Bakken <stig@php.net>
39 * @copyright 1997-2007 The PHP Group
40 * @license http://www.php.net/license/3_0.txt PHP License 3.0
41 * @version Release: 1.9.2
42 * @link http://pear.php.net/package/DB
44 class DB_storage extends PEAR
48 /** the name of the table (or view, if the backend database supports
49 * updates in views) we hold data from */
50 public $_table = null;
52 /** which column(s) in the table contains primary keys, can be a
53 * string for single-column primary keys, or an array of strings
54 * for multiple-column primary keys */
55 public $_keycolumn = null;
57 /** DB connection handle used for all transactions */
60 /** an assoc with the names of database fields stored as properties
62 public $_properties = array();
64 /** an assoc with the names of the properties in this object that
65 * have been changed since they were fetched from the database */
66 public $_changes = array();
68 /** flag that decides if data in this object can be changed.
69 * objects that don't have their table's key column in their
70 * property lists will be flagged as read-only. */
71 public $_readonly = false;
73 /** function or method that implements a validator for fields that
74 * are set, this validator function returns true if the field is
75 * valid, false if not */
76 public $_validator = null;
84 * @param $table string the name of the database table
86 * @param $keycolumn mixed string with name of key column, or array of
87 * strings if the table has a primary key of more than one column
89 * @param $dbh object database connection object
91 * @param $validator mixed function or method used to validate
92 * each new value, called with three parameters: the name of the
93 * field/column that is changing, a reference to the new value and
94 * a reference to this object
97 public function __construct($table, $keycolumn, &$dbh, $validator = null)
99 $this->PEAR('DB_Error');
100 $this->_table = $table;
101 $this->_keycolumn = $keycolumn;
103 $this->_readonly = false;
104 $this->_validator = $validator;
111 * Create a new (empty) row in the configured table for this
116 public function insert($newpk)
118 if (is_array($this->_keycolumn)) {
119 $primarykey = $this->_keycolumn;
121 $primarykey = array($this->_keycolumn);
123 settype($newpk, "array");
124 for ($i = 0; $i < sizeof($primarykey); $i++) {
125 $pkvals[] = $this->_dbh->quote($newpk[$i]);
128 $sth = $this->_dbh->query("INSERT INTO $this->_table (" .
129 implode(",", $primarykey) . ") VALUES(" .
130 implode(",", $pkvals) . ")");
131 if (DB::isError($sth)) {
134 if (sizeof($newpk) == 1) {
137 $this->setup($newpk);
145 * Method used to initialize a DB_storage object from the
148 * @param $keyval mixed the key[s] of the row to fetch (string or array)
152 public function setup($keyval)
154 $whereclause = $this->_makeWhere($keyval);
155 $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
156 $sth = $this->_dbh->query($query);
157 if (DB::isError($sth)) {
160 $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
161 if (DB::isError($row)) {
165 return $this->raiseError(
175 foreach ($row as $key => $value) {
176 $this->_properties[$key] = true;
177 $this->$key = $value;
186 * Utility method to build a "WHERE" clause to locate ourselves in
189 * XXX future improvement: use rowids?
192 * @param null $keyval
193 * @return mixed|string|null
195 public function _makeWhere($keyval = null)
197 if (is_array($this->_keycolumn)) {
198 if ($keyval === null) {
199 for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
200 $keyval[] = $this->{$this->_keycolumn[$i]};
204 for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
206 $whereclause .= ' AND ';
208 $whereclause .= $this->_keycolumn[$i];
209 if (is_null($keyval[$i])) {
210 // there's not much point in having a NULL key,
211 // but we support it anyway
212 $whereclause .= ' IS NULL';
214 $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]);
218 if ($keyval === null) {
219 $keyval = @$this->{$this->_keycolumn};
221 $whereclause = $this->_keycolumn;
222 if (is_null($keyval)) {
223 // there's not much point in having a NULL key,
224 // but we support it anyway
225 $whereclause .= ' IS NULL';
227 $whereclause .= ' = ' . $this->_dbh->quote($keyval);
237 * Output a simple description of this DB_storage object.
238 * @return string object description
240 public function toString()
242 $info = strtolower(get_class($this));
244 $info .= $this->_table;
245 $info .= ", keycolumn=";
246 if (is_array($this->_keycolumn)) {
247 $info .= "(" . implode(",", $this->_keycolumn) . ")";
249 $info .= $this->_keycolumn;
252 if (is_object($this->_dbh)) {
253 $info .= $this->_dbh->toString();
258 if (sizeof($this->_properties)) {
259 $info .= " [loaded, key=";
260 $keyname = $this->_keycolumn;
261 if (is_array($keyname)) {
263 for ($i = 0; $i < sizeof($keyname); $i++) {
267 $info .= $this->$keyname[$i];
271 $info .= $this->$keyname;
275 if (sizeof($this->_changes)) {
276 $info .= " [modified]";
285 * Dump the contents of this object to "standard output".
287 public function dump()
289 foreach ($this->_properties as $prop => $foo) {
291 print htmlentities($this->$prop);
300 * Static method used to create new DB storage objects.
302 * @param $data assoc. array where the keys are the names
303 * of properties/columns
304 * @return object a new instance of DB_storage or a subclass of it
306 public function &create($table, &$data)
308 $classname = strtolower(get_class($this));
309 $obj = new $classname($table);
310 foreach ($data as $name => $value) {
311 $obj->_properties[$name] = true;
312 $obj->$name = &$value;
318 // {{{ loadFromQuery()
321 * Loads data into this object from the given query. If this
322 * object already contains table data, changes will be saved and
323 * the object re-initialized first.
325 * @param $query SQL query
327 * @param $params parameter list in case you want to use
328 * prepare/execute mode
330 * @return int DB_OK on success, DB_WARNING_READ_ONLY if the
331 * returned object is read-only (because the object's specified
332 * key column was not found among the columns returned by $query),
333 * or another DB error code in case of errors.
335 // XXX commented out for now
337 function loadFromQuery($query, $params = null)
339 if (sizeof($this->_properties)) {
340 if (sizeof($this->_changes)) {
342 $this->_changes = array();
344 $this->_properties = array();
346 $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
347 if (DB::isError($rowdata)) {
351 $found_keycolumn = false;
352 while (list($key, $value) = each($rowdata)) {
353 if ($key == $this->_keycolumn) {
354 $found_keycolumn = true;
356 $this->_properties[$key] = true;
357 $this->$key = &$value;
358 unset($value); // have to unset, or all properties will
359 // refer to the same value
361 if (!$found_keycolumn) {
362 $this->_readonly = true;
363 return DB_WARNING_READ_ONLY;
373 * Modify an attriute value.
376 * @return bool|object
378 public function set($property, $newvalue)
380 // only change if $property is known and object is not
382 if ($this->_readonly) {
383 return $this->raiseError(
385 DB_WARNING_READ_ONLY,
393 if (@isset($this->_properties[$property])) {
394 if (empty($this->_validator)) {
397 $valid = @call_user_func(
407 $this->$property = $newvalue;
408 if (empty($this->_changes[$property])) {
409 $this->_changes[$property] = 0;
411 $this->_changes[$property]++;
414 return $this->raiseError(
419 "invalid field: $property",
426 return $this->raiseError(
428 DB_ERROR_NOSUCHFIELD,
431 "unknown field: $property",
441 * Fetch an attribute value.
443 * @param string attribute name
445 * @return attribute contents, or null if the attribute name is
448 public function &get($property)
450 // only return if $property is known
451 if (isset($this->_properties[$property])) {
452 return $this->$property;
462 * Destructor, calls DB_storage::store() if there are changes
463 * that are to be kept.
465 public function _DB_storage()
467 if (sizeof($this->_changes)) {
470 $this->_properties = array();
471 $this->_changes = array();
472 $this->_table = null;
479 * Stores changes to this object in the database.
483 public function store()
487 foreach ($this->_changes as $name => $foo) {
488 $params[] = &$this->$name;
489 $vars[] = $name . ' = ?';
492 $query = 'UPDATE ' . $this->_table . ' SET ' .
493 implode(', ', $vars) . ' WHERE ' .
495 $stmt = $this->_dbh->prepare($query);
496 $res = $this->_dbh->execute($stmt, $params);
497 if (DB::isError($res)) {
500 $this->_changes = array();
509 * Remove the row represented by this object from the database.
511 * @return mixed DB_OK or a DB error
513 public function remove()
515 if ($this->_readonly) {
516 return $this->raiseError(
518 DB_WARNING_READ_ONLY,
526 $query = 'DELETE FROM ' . $this->_table . ' WHERE ' .
528 $res = $this->_dbh->query($query);
529 if (DB::isError($res)) {
532 foreach ($this->_properties as $prop => $foo) {
535 $this->_properties = array();
536 $this->_changes = array();