4 * Abstract base class for representing objects that are stored in some DB table.
5 * This is basically an ORM-like wrapper around rows in database tables that
6 * aims to be both simple and very flexible. It is centered around an associative
7 * array of fields and various methods to do common interaction with the database.
9 * These methods must be implemented in deriving classes:
14 * These methods are likely candidates for overriding:
22 * Main instance methods:
28 * Main static methods:
40 * @file DBDataObject.php
42 * @licence GNU GPL v2 or later
43 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
45 abstract class DBDataObject
{
48 * The fields of the object.
49 * field name (w/o prefix) => value
54 protected $fields = array( 'id' => null );
63 * If the object should update summaries of linked items when changed.
64 * For example, update the course_count field in universities when a course in courses is deleted.
65 * Settings this to false can prevent needless updating work in situations
66 * such as deleting a university, which will then delete all it's courses.
71 protected $updateSummaries = true;
74 * Indicates if the object is in summary mode.
75 * This mode indicates that only summary fields got updated,
76 * which allows for optimizations.
81 protected $inSummaryMode = false;
84 * The database connection to use for read operations.
85 * Can be changed via @see setReadDb.
88 * @var integer DB_ enum
90 protected $readDb = DB_SLAVE
;
97 * @param array|null $fields
98 * @param boolean $loadDefaults
100 public function __construct( DBTable
$table, $fields = null, $loadDefaults = false ) {
101 $this->table
= $table;
103 if ( !is_array( $fields ) ) {
107 if ( $loadDefaults ) {
108 $fields = array_merge( $this->table
->getDefaults(), $fields );
111 $this->setFields( $fields );
115 * Load the specified fields from the database.
119 * @param array|null $fields
120 * @param boolean $override
121 * @param boolean $skipLoaded
123 * @return bool Success indicator
125 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
126 if ( is_null( $this->getId() ) ) {
130 if ( is_null( $fields ) ) {
131 $fields = array_keys( $this->getFieldTypes() );
135 $fields = array_diff( $fields, array_keys( $this->fields
) );
138 if ( count( $fields ) > 0 ) {
139 $result = $this->rawSelectRow(
140 $this->getPrefixedFields( $fields ),
141 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
142 array( 'LIMIT' => 1 )
145 if ( $result !== false ) {
146 $this->setFields( $this->getFieldsFromDBResult( $result ), $override );
157 * Gets the value of a field.
161 * @param string $name
162 * @param mixed $default
164 * @throws MWException
167 public function getField( $name, $default = null ) {
168 if ( $this->hasField( $name ) ) {
169 return $this->fields
[$name];
170 } elseif ( !is_null( $default ) ) {
173 throw new MWException( 'Attempted to get not-set field ' . $name );
178 * Gets the value of a field but first loads it if not done so already.
186 public function loadAndGetField( $name ) {
187 if ( !$this->hasField( $name ) ) {
188 $this->loadFields( array( $name ) );
191 return $this->getField( $name );
199 * @param string $name
201 public function removeField( $name ) {
202 unset( $this->fields
[$name] );
206 * Returns the objects database id.
210 * @return integer|null
212 public function getId() {
213 return $this->getField( 'id' );
217 * Sets the objects database id.
221 * @param integer|null $id
223 public function setId( $id ) {
224 return $this->setField( 'id', $id );
228 * Gets if a certain field is set.
232 * @param string $name
236 public function hasField( $name ) {
237 return array_key_exists( $name, $this->fields
);
241 * Gets if the id field is set.
247 public function hasIdField() {
248 return $this->hasField( 'id' )
249 && !is_null( $this->getField( 'id' ) );
253 * Sets multiple fields.
257 * @param array $fields The fields to set
258 * @param boolean $override Override already set fields with the provided values?
260 public function setFields( array $fields, $override = true ) {
261 foreach ( $fields as $name => $value ) {
262 if ( $override ||
!$this->hasField( $name ) ) {
263 $this->setField( $name, $value );
269 * Gets the fields => values to write to the table.
275 protected function getWriteValues() {
278 foreach ( $this->getFieldTypes() as $name => $type ) {
279 if ( array_key_exists( $name, $this->fields
) ) {
280 $value = $this->fields
[$name];
284 $value = (array)$value;
286 $value = serialize( $value );
289 $values[$this->getFieldPrefix() . $name] = $value;
297 * Serializes the object to an associative array which
298 * can then easily be converted into JSON or similar.
302 * @param null|array $fields
303 * @param boolean $incNullId
307 public function toArray( $fields = null, $incNullId = false ) {
309 $setFields = array();
311 if ( !is_array( $fields ) ) {
312 $setFields = $this->getSetFieldNames();
314 foreach ( $fields as $field ) {
315 if ( $this->hasField( $field ) ) {
316 $setFields[] = $field;
321 foreach ( $setFields as $field ) {
322 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
323 $data[$field] = $this->getField( $field );
331 * Load the default values, via getDefaults.
335 * @param boolean $override
337 public function loadDefaults( $override = true ) {
338 $this->setFields( $this->getDefaults(), $override );
342 * Writes the answer to the database, either updating it
343 * when it already exists, or inserting it when it doesn't.
347 * @return boolean Success indicator
349 public function save() {
350 if ( $this->hasIdField() ) {
351 return $this->saveExisting();
353 return $this->insert();
358 * Updates the object in the database.
362 * @return boolean Success indicator
364 protected function saveExisting() {
365 $dbw = wfGetDB( DB_MASTER
);
367 $success = $dbw->update(
369 $this->getWriteValues(),
370 array( $this->getFieldPrefix() . 'id' => $this->getId() ),
378 * Inserts the object into the database.
382 * @return boolean Success indicator
384 protected function insert() {
385 $dbw = wfGetDB( DB_MASTER
);
387 $result = $dbw->insert(
389 $this->getWriteValues(),
395 $this->setField( 'id', $dbw->insertId() );
402 * Removes the object from the database.
406 * @return boolean Success indicator
408 public function remove() {
409 $this->beforeRemove();
411 $success = static::delete( array( 'id' => $this->getId() ) );
421 * Gets called before an object is removed from the database.
425 protected function beforeRemove() {
426 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
430 * Before removal of an object happens, @see beforeRemove gets called.
431 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
432 * This allows for loading info needed after removal to get rid of linked data and the like.
438 protected function getBeforeRemoveFields() {
443 * Gets called after successfull removal.
444 * Can be overriden to get rid of linked data.
448 protected function onRemoved() {
449 $this->setField( 'id', null );
453 * Return the names and values of the fields.
459 public function getFields() {
460 return $this->fields
;
464 * Return the names of the fields.
470 public function getSetFieldNames() {
471 return array_keys( $this->fields
);
475 * Sets the value of a field.
476 * Strings can be provided for other types,
477 * so this method can be called from unserialization handlers.
481 * @param string $name
482 * @param mixed $value
484 * @throws MWException
486 public function setField( $name, $value ) {
487 $fields = $this->table
->getFieldTypes();
489 if ( array_key_exists( $name, $fields ) ) {
490 switch ( $fields[$name] ) {
492 $value = (int)$value;
495 $value = (float)$value;
498 if ( is_string( $value ) ) {
499 $value = $value !== '0';
500 } elseif ( is_int( $value ) ) {
501 $value = $value !== 0;
505 if ( is_string( $value ) ) {
506 $value = unserialize( $value );
509 if ( !is_array( $value ) ) {
514 if ( is_string( $value ) ) {
515 $value = unserialize( $value );
519 if ( is_string( $value ) ) {
520 $value = (int)$value;
525 $this->fields
[$name] = $value;
527 throw new MWException( 'Attempted to set unknown field ' . $name );
532 * Get a new instance of the class from an array.
537 * @param boolean $loadDefaults
539 * @return DBDataObject
541 public function newFromArray( array $data, $loadDefaults = false ) {
542 return new self( $data, $loadDefaults );
546 * Get the database type used for read operations.
550 * @return integer DB_ enum
552 public function getReadDb() {
553 return $this->readDb
;
557 * Set the database type to use for read operations.
563 public function setReadDb( $db ) {
568 * Gets if the object can take a certain field.
572 * @param string $name
576 public function canHaveField( $name ) {
577 return array_key_exists( $name, $this->table
->getFieldTypes() );
581 * Add an amount (can be negative) to the specified field (needs to be numeric).
585 * @param string $field
586 * @param integer $amount
588 * @return boolean Success indicator
590 public function addToField( $field, $amount ) {
591 if ( $amount == 0 ) {
595 if ( !$this->hasIdField() ) {
599 $absoluteAmount = abs( $amount );
600 $isNegative = $amount < 0;
602 $dbw = wfGetDB( DB_MASTER
);
604 $fullField = $this->getPrefixedField( $field );
606 $success = $dbw->update(
608 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
609 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
613 if ( $success && static::hasField( $field ) ) {
614 static::setField( $field, static::getField( $field ) +
$amount );
621 * Selects the the specified fields of the records matching the provided
622 * conditions. Field names do NOT get prefixed.
626 * @param array $fields
627 * @param array $conditions
628 * @param array $options
630 * @return ResultWrapper
632 protected static function rawSelectRow( array $fields, array $conditions = array(), array $options = array() ) {
633 $dbr = wfGetDB( static::getReadDb() );
635 return $dbr->selectRow(
636 static::getDBTable(),
645 * Return the names of the fields.
651 public function getFieldNames() {
652 return array_keys( $this->table
->getFieldTypes() );
656 * Computes and updates the values of the summary fields.
660 * @param array|string|null $summaryFields
662 public function loadSummaryFields( $summaryFields = null ) {
667 * Sets the value for the @see $updateSummaries field.
671 * @param boolean $update
673 public function setUpdateSummaries( $update ) {
674 $this->updateSummaries
= $update;
678 * Sets the value for the @see $inSummaryMode field.
682 * @param boolean $summaryMode
684 public function setSummaryMode( $summaryMode ) {
685 $this->inSummaryMode
= $summaryMode;
689 * Return if any fields got changed.
693 * @param DBDataObject $object
694 * @param boolean $excludeSummaryFields When set to true, summary field changes are ignored.
698 protected function fieldsChanged( DBDataObject
$object, $excludeSummaryFields = false ) {
699 foreach ( $this->fields
as $name => $value ) {
700 $excluded = $excludeSummaryFields && in_array( $name, $this->getSummaryFields() );
702 if ( !$excluded && $object->getField( $name ) !== $value ) {
710 protected function getDBTable() {
711 return $this->table
->getDBTable();
715 * Get an array with fields from a database result,
716 * that can be fed directly to the constructor or
721 * @param object $result
725 public function getFieldsFromDBResult( $result ) {
726 $result = (array)$result;
727 return array_combine(
728 $this->unprefixFieldNames( array_keys( $result ) ),
729 array_values( $result )
734 * Get a new instance of the class from a database result.
738 * @param stdClass $result
740 * @return DBDataObject
742 public function newFromDBResult( stdClass
$result ) {
743 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
747 * Returns the table this DBDataObject is a row in.
753 public function getTable() {