storage.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Provides an object interface to a table row
  5. *
  6. * PHP version 5
  7. *
  8. * LICENSE: This source file is subject to version 3.0 of the PHP license
  9. * that is available through the world-wide-web at the following URI:
  10. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  11. * the PHP License and are unable to obtain it through the web, please
  12. * send a note to license@php.net so we can mail you a copy immediately.
  13. *
  14. * @category Database
  15. * @package DB
  16. * @author Stig Bakken <stig@php.net>
  17. * @copyright 1997-2007 The PHP Group
  18. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  19. * @version CVS: $Id$
  20. * @link http://pear.php.net/package/DB
  21. */
  22. /**
  23. * Obtain the DB class so it can be extended from
  24. */
  25. require_once 'DB.php';
  26. /**
  27. * Provides an object interface to a table row
  28. *
  29. * It lets you add, delete and change rows using objects rather than SQL
  30. * statements.
  31. *
  32. * @category Database
  33. * @package DB
  34. * @author Stig Bakken <stig@php.net>
  35. * @copyright 1997-2007 The PHP Group
  36. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  37. * @version Release: 1.9.2
  38. * @link http://pear.php.net/package/DB
  39. */
  40. class DB_storage extends PEAR
  41. {
  42. // {{{ properties
  43. /** the name of the table (or view, if the backend database supports
  44. updates in views) we hold data from */
  45. public $_table = null;
  46. /** which column(s) in the table contains primary keys, can be a
  47. string for single-column primary keys, or an array of strings
  48. for multiple-column primary keys */
  49. public $_keycolumn = null;
  50. /** DB connection handle used for all transactions */
  51. public $_dbh = null;
  52. /** an assoc with the names of database fields stored as properties
  53. in this object */
  54. public $_properties = array();
  55. /** an assoc with the names of the properties in this object that
  56. have been changed since they were fetched from the database */
  57. public $_changes = array();
  58. /** flag that decides if data in this object can be changed.
  59. objects that don't have their table's key column in their
  60. property lists will be flagged as read-only. */
  61. public $_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. public $_validator = null;
  66. // }}}
  67. // {{{ constructor
  68. /**
  69. * Constructor
  70. *
  71. * @param $table string the name of the database table
  72. *
  73. * @param $keycolumn mixed string with name of key column, or array of
  74. * strings if the table has a primary key of more than one column
  75. *
  76. * @param $dbh object database connection object
  77. *
  78. * @param $validator mixed function or method used to validate
  79. * each new value, called with three parameters: the name of the
  80. * field/column that is changing, a reference to the new value and
  81. * a reference to this object
  82. *
  83. */
  84. public function __construct($table, $keycolumn, &$dbh, $validator = null)
  85. {
  86. $this->PEAR('DB_Error');
  87. $this->_table = $table;
  88. $this->_keycolumn = $keycolumn;
  89. $this->_dbh = $dbh;
  90. $this->_readonly = false;
  91. $this->_validator = $validator;
  92. }
  93. // }}}
  94. // {{{ _makeWhere()
  95. /**
  96. * Utility method to build a "WHERE" clause to locate ourselves in
  97. * the table.
  98. *
  99. * XXX future improvement: use rowids?
  100. *
  101. * @access private
  102. */
  103. public function _makeWhere($keyval = null)
  104. {
  105. if (is_array($this->_keycolumn)) {
  106. if ($keyval === null) {
  107. for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
  108. $keyval[] = $this->{$this->_keycolumn[$i]};
  109. }
  110. }
  111. $whereclause = '';
  112. for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
  113. if ($i > 0) {
  114. $whereclause .= ' AND ';
  115. }
  116. $whereclause .= $this->_keycolumn[$i];
  117. if (is_null($keyval[$i])) {
  118. // there's not much point in having a NULL key,
  119. // but we support it anyway
  120. $whereclause .= ' IS NULL';
  121. } else {
  122. $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]);
  123. }
  124. }
  125. } else {
  126. if ($keyval === null) {
  127. $keyval = @$this->{$this->_keycolumn};
  128. }
  129. $whereclause = $this->_keycolumn;
  130. if (is_null($keyval)) {
  131. // there's not much point in having a NULL key,
  132. // but we support it anyway
  133. $whereclause .= ' IS NULL';
  134. } else {
  135. $whereclause .= ' = ' . $this->_dbh->quote($keyval);
  136. }
  137. }
  138. return $whereclause;
  139. }
  140. // }}}
  141. // {{{ setup()
  142. /**
  143. * Method used to initialize a DB_storage object from the
  144. * configured table.
  145. *
  146. * @param $keyval mixed the key[s] of the row to fetch (string or array)
  147. *
  148. * @return int DB_OK on success, a DB error if not
  149. */
  150. public function setup($keyval)
  151. {
  152. $whereclause = $this->_makeWhere($keyval);
  153. $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
  154. $sth = $this->_dbh->query($query);
  155. if (DB::isError($sth)) {
  156. return $sth;
  157. }
  158. $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
  159. if (DB::isError($row)) {
  160. return $row;
  161. }
  162. if (!$row) {
  163. return $this->raiseError(
  164. null,
  165. DB_ERROR_NOT_FOUND,
  166. null,
  167. null,
  168. $query,
  169. null,
  170. true
  171. );
  172. }
  173. foreach ($row as $key => $value) {
  174. $this->_properties[$key] = true;
  175. $this->$key = $value;
  176. }
  177. return DB_OK;
  178. }
  179. // }}}
  180. // {{{ insert()
  181. /**
  182. * Create a new (empty) row in the configured table for this
  183. * object.
  184. */
  185. public function insert($newpk)
  186. {
  187. if (is_array($this->_keycolumn)) {
  188. $primarykey = $this->_keycolumn;
  189. } else {
  190. $primarykey = array($this->_keycolumn);
  191. }
  192. settype($newpk, "array");
  193. for ($i = 0; $i < sizeof($primarykey); $i++) {
  194. $pkvals[] = $this->_dbh->quote($newpk[$i]);
  195. }
  196. $sth = $this->_dbh->query("INSERT INTO $this->_table (" .
  197. implode(",", $primarykey) . ") VALUES(" .
  198. implode(",", $pkvals) . ")");
  199. if (DB::isError($sth)) {
  200. return $sth;
  201. }
  202. if (sizeof($newpk) == 1) {
  203. $newpk = $newpk[0];
  204. }
  205. $this->setup($newpk);
  206. }
  207. // }}}
  208. // {{{ toString()
  209. /**
  210. * Output a simple description of this DB_storage object.
  211. * @return string object description
  212. */
  213. public function toString()
  214. {
  215. $info = strtolower(get_class($this));
  216. $info .= " (table=";
  217. $info .= $this->_table;
  218. $info .= ", keycolumn=";
  219. if (is_array($this->_keycolumn)) {
  220. $info .= "(" . implode(",", $this->_keycolumn) . ")";
  221. } else {
  222. $info .= $this->_keycolumn;
  223. }
  224. $info .= ", dbh=";
  225. if (is_object($this->_dbh)) {
  226. $info .= $this->_dbh->toString();
  227. } else {
  228. $info .= "null";
  229. }
  230. $info .= ")";
  231. if (sizeof($this->_properties)) {
  232. $info .= " [loaded, key=";
  233. $keyname = $this->_keycolumn;
  234. if (is_array($keyname)) {
  235. $info .= "(";
  236. for ($i = 0; $i < sizeof($keyname); $i++) {
  237. if ($i > 0) {
  238. $info .= ",";
  239. }
  240. $info .= $this->$keyname[$i];
  241. }
  242. $info .= ")";
  243. } else {
  244. $info .= $this->$keyname;
  245. }
  246. $info .= "]";
  247. }
  248. if (sizeof($this->_changes)) {
  249. $info .= " [modified]";
  250. }
  251. return $info;
  252. }
  253. // }}}
  254. // {{{ dump()
  255. /**
  256. * Dump the contents of this object to "standard output".
  257. */
  258. public function dump()
  259. {
  260. foreach ($this->_properties as $prop => $foo) {
  261. print "$prop = ";
  262. print htmlentities($this->$prop);
  263. print "<br />\n";
  264. }
  265. }
  266. // }}}
  267. // {{{ &create()
  268. /**
  269. * Static method used to create new DB storage objects.
  270. * @param $data assoc. array where the keys are the names
  271. * of properties/columns
  272. * @return object a new instance of DB_storage or a subclass of it
  273. */
  274. public function &create($table, &$data)
  275. {
  276. $classname = strtolower(get_class($this));
  277. $obj = new $classname($table);
  278. foreach ($data as $name => $value) {
  279. $obj->_properties[$name] = true;
  280. $obj->$name = &$value;
  281. }
  282. return $obj;
  283. }
  284. // }}}
  285. // {{{ loadFromQuery()
  286. /**
  287. * Loads data into this object from the given query. If this
  288. * object already contains table data, changes will be saved and
  289. * the object re-initialized first.
  290. *
  291. * @param $query SQL query
  292. *
  293. * @param $params parameter list in case you want to use
  294. * prepare/execute mode
  295. *
  296. * @return int DB_OK on success, DB_WARNING_READ_ONLY if the
  297. * returned object is read-only (because the object's specified
  298. * key column was not found among the columns returned by $query),
  299. * or another DB error code in case of errors.
  300. */
  301. // XXX commented out for now
  302. /*
  303. function loadFromQuery($query, $params = null)
  304. {
  305. if (sizeof($this->_properties)) {
  306. if (sizeof($this->_changes)) {
  307. $this->store();
  308. $this->_changes = array();
  309. }
  310. $this->_properties = array();
  311. }
  312. $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
  313. if (DB::isError($rowdata)) {
  314. return $rowdata;
  315. }
  316. reset($rowdata);
  317. $found_keycolumn = false;
  318. while (list($key, $value) = each($rowdata)) {
  319. if ($key == $this->_keycolumn) {
  320. $found_keycolumn = true;
  321. }
  322. $this->_properties[$key] = true;
  323. $this->$key = &$value;
  324. unset($value); // have to unset, or all properties will
  325. // refer to the same value
  326. }
  327. if (!$found_keycolumn) {
  328. $this->_readonly = true;
  329. return DB_WARNING_READ_ONLY;
  330. }
  331. return DB_OK;
  332. }
  333. */
  334. // }}}
  335. // {{{ set()
  336. /**
  337. * Modify an attriute value.
  338. */
  339. public function set($property, $newvalue)
  340. {
  341. // only change if $property is known and object is not
  342. // read-only
  343. if ($this->_readonly) {
  344. return $this->raiseError(
  345. null,
  346. DB_WARNING_READ_ONLY,
  347. null,
  348. null,
  349. null,
  350. null,
  351. true
  352. );
  353. }
  354. if (@isset($this->_properties[$property])) {
  355. if (empty($this->_validator)) {
  356. $valid = true;
  357. } else {
  358. $valid = @call_user_func(
  359. $this->_validator,
  360. $this->_table,
  361. $property,
  362. $newvalue,
  363. $this->$property,
  364. $this
  365. );
  366. }
  367. if ($valid) {
  368. $this->$property = $newvalue;
  369. if (empty($this->_changes[$property])) {
  370. $this->_changes[$property] = 0;
  371. } else {
  372. $this->_changes[$property]++;
  373. }
  374. } else {
  375. return $this->raiseError(
  376. null,
  377. DB_ERROR_INVALID,
  378. null,
  379. null,
  380. "invalid field: $property",
  381. null,
  382. true
  383. );
  384. }
  385. return true;
  386. }
  387. return $this->raiseError(
  388. null,
  389. DB_ERROR_NOSUCHFIELD,
  390. null,
  391. null,
  392. "unknown field: $property",
  393. null,
  394. true
  395. );
  396. }
  397. // }}}
  398. // {{{ &get()
  399. /**
  400. * Fetch an attribute value.
  401. *
  402. * @param string attribute name
  403. *
  404. * @return attribute contents, or null if the attribute name is
  405. * unknown
  406. */
  407. public function &get($property)
  408. {
  409. // only return if $property is known
  410. if (isset($this->_properties[$property])) {
  411. return $this->$property;
  412. }
  413. $tmp = null;
  414. return $tmp;
  415. }
  416. // }}}
  417. // {{{ _DB_storage()
  418. /**
  419. * Destructor, calls DB_storage::store() if there are changes
  420. * that are to be kept.
  421. */
  422. public function _DB_storage()
  423. {
  424. if (sizeof($this->_changes)) {
  425. $this->store();
  426. }
  427. $this->_properties = array();
  428. $this->_changes = array();
  429. $this->_table = null;
  430. }
  431. // }}}
  432. // {{{ store()
  433. /**
  434. * Stores changes to this object in the database.
  435. *
  436. * @return DB_OK or a DB error
  437. */
  438. public function store()
  439. {
  440. $params = array();
  441. $vars = array();
  442. foreach ($this->_changes as $name => $foo) {
  443. $params[] = &$this->$name;
  444. $vars[] = $name . ' = ?';
  445. }
  446. if ($vars) {
  447. $query = 'UPDATE ' . $this->_table . ' SET ' .
  448. implode(', ', $vars) . ' WHERE ' .
  449. $this->_makeWhere();
  450. $stmt = $this->_dbh->prepare($query);
  451. $res = $this->_dbh->execute($stmt, $params);
  452. if (DB::isError($res)) {
  453. return $res;
  454. }
  455. $this->_changes = array();
  456. }
  457. return DB_OK;
  458. }
  459. // }}}
  460. // {{{ remove()
  461. /**
  462. * Remove the row represented by this object from the database.
  463. *
  464. * @return mixed DB_OK or a DB error
  465. */
  466. public function remove()
  467. {
  468. if ($this->_readonly) {
  469. return $this->raiseError(
  470. null,
  471. DB_WARNING_READ_ONLY,
  472. null,
  473. null,
  474. null,
  475. null,
  476. true
  477. );
  478. }
  479. $query = 'DELETE FROM ' . $this->_table .' WHERE '.
  480. $this->_makeWhere();
  481. $res = $this->_dbh->query($query);
  482. if (DB::isError($res)) {
  483. return $res;
  484. }
  485. foreach ($this->_properties as $prop => $foo) {
  486. unset($this->$prop);
  487. }
  488. $this->_properties = array();
  489. $this->_changes = array();
  490. return DB_OK;
  491. }
  492. // }}}
  493. }
  494. /*
  495. * Local variables:
  496. * tab-width: 4
  497. * c-basic-offset: 4
  498. * End:
  499. */