2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license, |
9 // | that is bundled with this package in the file LICENSE, and is |
10 // | available at through the world-wide-web at |
11 // | http://www.php.net/license/2_02.txt. |
12 // | If you did not receive a copy of the PHP license and are unable to |
13 // | obtain it through the world-wide-web, please send a note to |
14 // | license@php.net so we can mail you a copy immediately. |
15 // +----------------------------------------------------------------------+
16 // | Author: Stig Bakken <stig@php.net> |
17 // | Maintainer: Daniel Convissor <danielc@php.net> |
18 // +----------------------------------------------------------------------+
20 require_once 'DB.php';
23 * Provides an object interface to a table row.
25 * It lets you add, delete and change rows using objects rather than SQL
31 * @author Stig Bakken <stig@php.net>
33 class DB_storage extends PEAR
37 /** the name of the table (or view, if the backend database supports
38 updates in views) we hold data from */
41 /** which column(s) in the table contains primary keys, can be a
42 string for single-column primary keys, or an array of strings
43 for multiple-column primary keys */
44 var $_keycolumn = null;
46 /** DB connection handle used for all transactions */
49 /** an assoc with the names of database fields stored as properties
51 var $_properties = array();
53 /** an assoc with the names of the properties in this object that
54 have been changed since they were fetched from the database */
55 var $_changes = array();
57 /** flag that decides if data in this object can be changed.
58 objects that don't have their table's key column in their
59 property lists will be flagged as read-only. */
60 var $_readonly = false;
62 /** function or method that implements a validator for fields that
63 are set, this validator function returns true if the field is
64 valid, false if not */
65 var $_validator = null;
73 * @param $table string the name of the database table
75 * @param $keycolumn mixed string with name of key column, or array of
76 * strings if the table has a primary key of more than one column
78 * @param $dbh object database connection object
80 * @param $validator mixed function or method used to validate
81 * each new value, called with three parameters: the name of the
82 * field/column that is changing, a reference to the new value and
83 * a reference to this object
86 function DB_storage($table, $keycolumn, &$dbh, $validator = null)
88 $this->PEAR('DB_Error');
89 $this->_table = $table;
90 $this->_keycolumn = $keycolumn;
92 $this->_readonly = false;
93 $this->_validator = $validator;
100 * Utility method to build a "WHERE" clause to locate ourselves in
103 * XXX future improvement: use rowids?
107 function _makeWhere($keyval = null)
109 if (is_array($this->_keycolumn)) {
110 if ($keyval === null) {
111 for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
112 $keyval[] = $this->{$this->_keycolumn[$i]};
116 for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
118 $whereclause .= ' AND ';
120 $whereclause .= $this->_keycolumn[$i];
121 if (is_null($keyval[$i])) {
122 // there's not much point in having a NULL key,
123 // but we support it anyway
124 $whereclause .= ' IS NULL';
126 $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]);
130 if ($keyval === null) {
131 $keyval = @$this->{$this->_keycolumn};
133 $whereclause = $this->_keycolumn;
134 if (is_null($keyval)) {
135 // there's not much point in having a NULL key,
136 // but we support it anyway
137 $whereclause .= ' IS NULL';
139 $whereclause .= ' = ' . $this->_dbh->quote($keyval);
149 * Method used to initialize a DB_storage object from the
152 * @param $keyval mixed the key[s] of the row to fetch (string or array)
154 * @return int DB_OK on success, a DB error if not
156 function setup($keyval)
158 $whereclause = $this->_makeWhere($keyval);
159 $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
160 $sth = $this->_dbh->query($query);
161 if (DB::isError($sth)) {
164 $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
165 if (DB::isError($row)) {
169 return $this->raiseError(null, DB_ERROR_NOT_FOUND, null, null,
172 foreach ($row as $key => $value) {
173 $this->_properties[$key] = true;
174 $this->$key = $value;
183 * Create a new (empty) row in the configured table for this
186 function insert($newpk)
188 if (is_array($this->_keycolumn)) {
189 $primarykey = $this->_keycolumn;
191 $primarykey = array($this->_keycolumn);
193 settype($newpk, "array");
194 for ($i = 0; $i < sizeof($primarykey); $i++) {
195 $pkvals[] = $this->_dbh->quote($newpk[$i]);
198 $sth = $this->_dbh->query("INSERT INTO $this->_table (" .
199 implode(",", $primarykey) . ") VALUES(" .
200 implode(",", $pkvals) . ")");
201 if (DB::isError($sth)) {
204 if (sizeof($newpk) == 1) {
207 $this->setup($newpk);
214 * Output a simple description of this DB_storage object.
215 * @return string object description
219 $info = strtolower(get_class($this));
221 $info .= $this->_table;
222 $info .= ", keycolumn=";
223 if (is_array($this->_keycolumn)) {
224 $info .= "(" . implode(",", $this->_keycolumn) . ")";
226 $info .= $this->_keycolumn;
229 if (is_object($this->_dbh)) {
230 $info .= $this->_dbh->toString();
235 if (sizeof($this->_properties)) {
236 $info .= " [loaded, key=";
237 $keyname = $this->_keycolumn;
238 if (is_array($keyname)) {
240 for ($i = 0; $i < sizeof($keyname); $i++) {
244 $info .= $this->$keyname[$i];
248 $info .= $this->$keyname;
252 if (sizeof($this->_changes)) {
253 $info .= " [modified]";
262 * Dump the contents of this object to "standard output".
266 foreach ($this->_properties as $prop => $foo) {
268 print htmlentities($this->$prop);
277 * Static method used to create new DB storage objects.
278 * @param $data assoc. array where the keys are the names
279 * of properties/columns
280 * @return object a new instance of DB_storage or a subclass of it
282 function &create($table, &$data)
284 $classname = strtolower(get_class($this));
285 $obj =& new $classname($table);
286 foreach ($data as $name => $value) {
287 $obj->_properties[$name] = true;
288 $obj->$name = &$value;
294 // {{{ loadFromQuery()
297 * Loads data into this object from the given query. If this
298 * object already contains table data, changes will be saved and
299 * the object re-initialized first.
301 * @param $query SQL query
303 * @param $params parameter list in case you want to use
304 * prepare/execute mode
306 * @return int DB_OK on success, DB_WARNING_READ_ONLY if the
307 * returned object is read-only (because the object's specified
308 * key column was not found among the columns returned by $query),
309 * or another DB error code in case of errors.
311 // XXX commented out for now
313 function loadFromQuery($query, $params = null)
315 if (sizeof($this->_properties)) {
316 if (sizeof($this->_changes)) {
318 $this->_changes = array();
320 $this->_properties = array();
322 $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
323 if (DB::isError($rowdata)) {
327 $found_keycolumn = false;
328 while (list($key, $value) = each($rowdata)) {
329 if ($key == $this->_keycolumn) {
330 $found_keycolumn = true;
332 $this->_properties[$key] = true;
333 $this->$key = &$value;
334 unset($value); // have to unset, or all properties will
335 // refer to the same value
337 if (!$found_keycolumn) {
338 $this->_readonly = true;
339 return DB_WARNING_READ_ONLY;
349 * Modify an attriute value.
351 function set($property, $newvalue)
353 // only change if $property is known and object is not
355 if ($this->_readonly) {
356 return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
357 null, null, null, true);
359 if (@isset($this->_properties[$property])) {
360 if (empty($this->_validator)) {
363 $valid = @call_user_func($this->_validator,
371 $this->$property = $newvalue;
372 if (empty($this->_changes[$property])) {
373 $this->_changes[$property] = 0;
375 $this->_changes[$property]++;
378 return $this->raiseError(null, DB_ERROR_INVALID, null,
379 null, "invalid field: $property",
384 return $this->raiseError(null, DB_ERROR_NOSUCHFIELD, null,
385 null, "unknown field: $property",
393 * Fetch an attribute value.
395 * @param string attribute name
397 * @return attribute contents, or null if the attribute name is
400 function &get($property)
402 // only return if $property is known
403 if (isset($this->_properties[$property])) {
404 return $this->$property;
414 * Destructor, calls DB_storage::store() if there are changes
415 * that are to be kept.
417 function _DB_storage()
419 if (sizeof($this->_changes)) {
422 $this->_properties = array();
423 $this->_changes = array();
424 $this->_table = null;
431 * Stores changes to this object in the database.
433 * @return DB_OK or a DB error
437 foreach ($this->_changes as $name => $foo) {
438 $params[] = &$this->$name;
439 $vars[] = $name . ' = ?';
442 $query = 'UPDATE ' . $this->_table . ' SET ' .
443 implode(', ', $vars) . ' WHERE ' .
445 $stmt = $this->_dbh->prepare($query);
446 $res = $this->_dbh->execute($stmt, $params);
447 if (DB::isError($res)) {
450 $this->_changes = array();
459 * Remove the row represented by this object from the database.
461 * @return mixed DB_OK or a DB error
465 if ($this->_readonly) {
466 return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
467 null, null, null, true);
469 $query = 'DELETE FROM ' . $this->_table .' WHERE '.
471 $res = $this->_dbh->query($query);
472 if (DB::isError($res)) {
475 foreach ($this->_properties as $prop => $foo) {
478 $this->_properties = array();
479 $this->_changes = array();