69a7fbb1e9d12e845ea7c2b3f16244c144a8f3b4
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 );
57 * If the object should update summaries of linked items when changed.
58 * For example, update the course_count field in universities when a course in courses is deleted.
59 * Settings this to false can prevent needless updating work in situations
60 * such as deleting a university, which will then delete all it's courses.
65 protected $updateSummaries = true;
68 * Indicates if the object is in summary mode.
69 * This mode indicates that only summary fields got updated,
70 * which allows for optimizations.
75 protected $inSummaryMode = false;
79 * The database connection to use for read operations.
80 * Can be changed via @see setReadDb.
83 * @var integer DB_ enum
85 protected static $readDb = DB_SLAVE
;
88 * Returns the name of the database table objects of this type are stored in.
95 public static function getDBTable() {
96 throw new MWException( 'Class "' . get_called_class() . '" did not implement getDBTable' );
100 * Gets the db field prefix.
104 * @throws MWException
107 protected static function getFieldPrefix() {
108 throw new MWException( 'Class "' . get_called_class() . '" did not implement getFieldPrefix' );
112 * Returns an array with the fields and their types this object contains.
113 * This corresponds directly to the fields in the database, without prefix.
127 * @throws MWException
130 protected static function getFieldTypes() {
131 throw new MWException( 'Class did not implement getFieldTypes' );
135 * Returns a list of default field values.
136 * field name => field value
142 public static function getDefaults() {
147 * Returns a list of the summary fields.
148 * These are fields that cache computed values, such as the amount of linked objects of $type.
149 * This is relevant as one might not want to do actions such as log changes when these get updated.
155 public static function getSummaryFields() {
164 * @param array|null $fields
165 * @param boolean $loadDefaults
167 public function __construct( $fields = null, $loadDefaults = false ) {
168 if ( !is_array( $fields ) ) {
172 if ( $loadDefaults ) {
173 $fields = array_merge( $this->getDefaults(), $fields );
176 $this->setFields( $fields );
180 * Load the specified fields from the database.
184 * @param array|null $fields
185 * @param boolean $override
186 * @param boolean $skipLoaded
188 * @return bool Success indicator
190 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
191 if ( is_null( $this->getId() ) ) {
195 if ( is_null( $fields ) ) {
196 $fields = array_keys( $this->getFieldTypes() );
200 $fields = array_diff( $fields, array_keys( $this->fields
) );
203 if ( count( $fields ) > 0 ) {
204 $result = $this->rawSelectRow(
205 $this->getPrefixedFields( $fields ),
206 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
207 array( 'LIMIT' => 1 )
210 if ( $result !== false ) {
211 $this->setFields( $this->getFieldsFromDBResult( $result ), $override );
222 * Gets the value of a field.
226 * @param string $name
227 * @param mixed $default
229 * @throws MWException
232 public function getField( $name, $default = null ) {
233 if ( $this->hasField( $name ) ) {
234 return $this->fields
[$name];
235 } elseif ( !is_null( $default ) ) {
238 throw new MWException( 'Attempted to get not-set field ' . $name );
243 * Gets the value of a field but first loads it if not done so already.
251 public function loadAndGetField( $name ) {
252 if ( !$this->hasField( $name ) ) {
253 $this->loadFields( array( $name ) );
256 return $this->getField( $name );
264 * @param string $name
266 public function removeField( $name ) {
267 unset( $this->fields
[$name] );
271 * Returns the objects database id.
275 * @return integer|null
277 public function getId() {
278 return $this->getField( 'id' );
282 * Sets the objects database id.
286 * @param integer|null $id
288 public function setId( $id ) {
289 return $this->setField( 'id', $id );
293 * Gets if a certain field is set.
297 * @param string $name
301 public function hasField( $name ) {
302 return array_key_exists( $name, $this->fields
);
306 * Gets if the id field is set.
312 public function hasIdField() {
313 return $this->hasField( 'id' )
314 && !is_null( $this->getField( 'id' ) );
318 * Sets multiple fields.
322 * @param array $fields The fields to set
323 * @param boolean $override Override already set fields with the provided values?
325 public function setFields( array $fields, $override = true ) {
326 foreach ( $fields as $name => $value ) {
327 if ( $override ||
!$this->hasField( $name ) ) {
328 $this->setField( $name, $value );
334 * Gets the fields => values to write to the table.
340 protected function getWriteValues() {
343 foreach ( $this->getFieldTypes() as $name => $type ) {
344 if ( array_key_exists( $name, $this->fields
) ) {
345 $value = $this->fields
[$name];
349 $value = (array)$value;
351 $value = serialize( $value );
354 $values[$this->getFieldPrefix() . $name] = $value;
362 * Serializes the object to an associative array which
363 * can then easily be converted into JSON or similar.
367 * @param null|array $fields
368 * @param boolean $incNullId
372 public function toArray( $fields = null, $incNullId = false ) {
374 $setFields = array();
376 if ( !is_array( $fields ) ) {
377 $setFields = $this->getSetFieldNames();
379 foreach ( $fields as $field ) {
380 if ( $this->hasField( $field ) ) {
381 $setFields[] = $field;
386 foreach ( $setFields as $field ) {
387 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
388 $data[$field] = $this->getField( $field );
396 * Load the default values, via getDefaults.
400 * @param boolean $override
402 public function loadDefaults( $override = true ) {
403 $this->setFields( $this->getDefaults(), $override );
407 * Writes the answer to the database, either updating it
408 * when it already exists, or inserting it when it doesn't.
412 * @return boolean Success indicator
414 public function save() {
415 if ( $this->hasIdField() ) {
416 return $this->saveExisting();
418 return $this->insert();
423 * Updates the object in the database.
427 * @return boolean Success indicator
429 protected function saveExisting() {
430 $dbw = wfGetDB( DB_MASTER
);
432 $success = $dbw->update(
434 $this->getWriteValues(),
435 array( $this->getFieldPrefix() . 'id' => $this->getId() ),
443 * Inserts the object into the database.
447 * @return boolean Success indicator
449 protected function insert() {
450 $dbw = wfGetDB( DB_MASTER
);
452 $result = $dbw->insert(
454 $this->getWriteValues(),
460 $this->setField( 'id', $dbw->insertId() );
467 * Removes the object from the database.
471 * @return boolean Success indicator
473 public function remove() {
474 $this->beforeRemove();
476 $success = static::delete( array( 'id' => $this->getId() ) );
486 * Gets called before an object is removed from the database.
490 protected function beforeRemove() {
491 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
495 * Before removal of an object happens, @see beforeRemove gets called.
496 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
497 * This allows for loading info needed after removal to get rid of linked data and the like.
503 protected function getBeforeRemoveFields() {
508 * Gets called after successfull removal.
509 * Can be overriden to get rid of linked data.
513 protected function onRemoved() {
514 $this->setField( 'id', null );
518 * Return the names and values of the fields.
524 public function getFields() {
525 return $this->fields
;
529 * Return the names of the fields.
535 public function getSetFieldNames() {
536 return array_keys( $this->fields
);
540 * Sets the value of a field.
541 * Strings can be provided for other types,
542 * so this method can be called from unserialization handlers.
546 * @param string $name
547 * @param mixed $value
549 * @throws MWException
551 public function setField( $name, $value ) {
552 $fields = $this->getFieldTypes();
554 if ( array_key_exists( $name, $fields ) ) {
555 switch ( $fields[$name] ) {
557 $value = (int)$value;
560 $value = (float)$value;
563 if ( is_string( $value ) ) {
564 $value = $value !== '0';
565 } elseif ( is_int( $value ) ) {
566 $value = $value !== 0;
570 if ( is_string( $value ) ) {
571 $value = unserialize( $value );
574 if ( !is_array( $value ) ) {
579 if ( is_string( $value ) ) {
580 $value = unserialize( $value );
584 if ( is_string( $value ) ) {
585 $value = (int)$value;
590 $this->fields
[$name] = $value;
592 throw new MWException( 'Attempted to set unknown field ' . $name );
597 * Get a new instance of the class from an array.
602 * @param boolean $loadDefaults
604 * @return DBDataObject
606 public static function newFromArray( array $data, $loadDefaults = false ) {
607 return new static( $data, $loadDefaults );
611 * Get the database type used for read operations.
614 * @return integer DB_ enum
616 public static function getReadDb() {
617 return self
::$readDb;
621 * Set the database type to use for read operations.
627 public static function setReadDb( $db ) {
632 * Gets if the object can take a certain field.
636 * @param string $name
640 public static function canHaveField( $name ) {
641 return array_key_exists( $name, static::getFieldTypes() );
645 * Takes in a field or array of fields and returns an
646 * array with their prefixed versions, ready for db usage.
650 * @param array|string $fields
654 public static function getPrefixedFields( array $fields ) {
655 foreach ( $fields as &$field ) {
656 $field = static::getPrefixedField( $field );
663 * Takes in a field and returns an it's prefixed version, ready for db usage.
667 * @param string|array $field
670 * @throws MWException
672 public static function getPrefixedField( $field ) {
673 return static::getFieldPrefix() . $field;
677 * Takes in an associative array with field names as keys and
678 * their values as value. The field names are prefixed with the
681 * Field names can also be provided as an array with as first element a table name, such as
682 * $conditions = array(
683 * array( array( 'tablename', 'fieldname' ), $value ),
688 * @param array $values
692 public static function getPrefixedValues( array $values ) {
693 $prefixedValues = array();
695 foreach ( $values as $field => $value ) {
696 if ( is_integer( $field ) ) {
697 if ( is_array( $value ) ) {
702 $value = explode( ' ', $value, 2 );
703 $value[0] = static::getPrefixedField( $value[0] );
704 $prefixedValues[] = implode( ' ', $value );
709 $prefixedValues[static::getPrefixedField( $field )] = $value;
712 return $prefixedValues;
716 * Get an array with fields from a database result,
717 * that can be fed directly to the constructor or
722 * @param object $result
726 public static function getFieldsFromDBResult( $result ) {
727 $result = (array)$result;
728 return array_combine(
729 static::unprefixFieldNames( array_keys( $result ) ),
730 array_values( $result )
735 * Takes a field name with prefix and returns the unprefixed equivalent.
739 * @param string $fieldName
743 public static function unprefixFieldName( $fieldName ) {
744 return substr( $fieldName, strlen( static::getFieldPrefix() ) );
748 * Takes an array of field names with prefix and returns the unprefixed equivalent.
752 * @param array $fieldNames
756 public static function unprefixFieldNames( array $fieldNames ) {
757 return array_map( 'static::unprefixFieldName', $fieldNames );
761 * Get a new instance of the class from a database result.
765 * @param stdClass $result
767 * @return DBDataObject
769 public static function newFromDBResult( stdClass
$result ) {
770 return static::newFromArray( static::getFieldsFromDBResult( $result ) );
774 * Removes the object from the database.
778 * @param array $conditions
780 * @return boolean Success indicator
782 public static function delete( array $conditions ) {
783 return wfGetDB( DB_MASTER
)->delete(
784 static::getDBTable(),
785 static::getPrefixedValues( $conditions )
790 * Add an amount (can be negative) to the specified field (needs to be numeric).
794 * @param string $field
795 * @param integer $amount
797 * @return boolean Success indicator
799 public static function addToField( $field, $amount ) {
800 if ( $amount == 0 ) {
804 if ( !static::hasIdField() ) {
808 $absoluteAmount = abs( $amount );
809 $isNegative = $amount < 0;
811 $dbw = wfGetDB( DB_MASTER
);
813 $fullField = static::getPrefixedField( $field );
815 $success = $dbw->update(
816 static::getDBTable(),
817 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
818 array( static::getPrefixedField( 'id' ) => static::getId() ),
822 if ( $success && static::hasField( $field ) ) {
823 static::setField( $field, static::getField( $field ) +
$amount );
830 * Selects the the specified fields of the records matching the provided
831 * conditions and returns them as DBDataObject. Field names get prefixed.
835 * @param array|string|null $fields
836 * @param array $conditions
837 * @param array $options
839 * @return array of self
841 public static function select( $fields = null, array $conditions = array(), array $options = array() ) {
842 $result = static::selectFields( $fields, $conditions, $options, false );
846 foreach ( $result as $record ) {
847 $objects[] = static::newFromArray( $record );
854 * Selects the the specified fields of the records matching the provided
855 * conditions and returns them as associative arrays.
856 * Provided field names get prefixed.
857 * Returned field names will not have a prefix.
859 * When $collapse is true:
860 * If one field is selected, each item in the result array will be this field.
861 * If two fields are selected, each item in the result array will have as key
862 * the first field and as value the second field.
863 * If more then two fields are selected, each item will be an associative array.
867 * @param array|string|null $fields
868 * @param array $conditions
869 * @param array $options
870 * @param boolean $collapse Set to false to always return each result row as associative array.
872 * @return array of array
874 public static function selectFields( $fields = null, array $conditions = array(), array $options = array(), $collapse = true ) {
875 if ( is_null( $fields ) ) {
876 $fields = array_keys( static::getFieldTypes() );
879 $fields = (array)$fields;
882 $dbr = wfGetDB( static::getReadDb() );
883 $result = $dbr->select(
884 static::getDBTable(),
885 static::getPrefixedFields( $fields ),
886 static::getPrefixedValues( $conditions ),
893 foreach ( $result as $record ) {
894 $objects[] = static::getFieldsFromDBResult( $record );
898 if ( count( $fields ) === 1 ) {
899 $objects = array_map( 'array_shift', $objects );
901 elseif ( count( $fields ) === 2 ) {
904 foreach ( $objects as $object ) {
905 $o[array_shift( $object )] = array_shift( $object );
916 * Selects the the specified fields of the first matching record.
917 * Field names get prefixed.
921 * @param array|string|null $fields
922 * @param array $conditions
923 * @param array $options
925 * @return DBObject|bool False on failure
927 public static function selectRow( $fields = null, array $conditions = array(), array $options = array() ) {
928 $options['LIMIT'] = 1;
930 $objects = static::select( $fields, $conditions, $options );
932 return count( $objects ) > 0 ?
$objects[0] : false;
936 * Selects the the specified fields of the first record matching the provided
937 * conditions and returns it as an associative array, or false when nothing matches.
938 * This method makes use of selectFields and expects the same parameters and
939 * returns the same results (if there are any, if there are none, this method returns false).
940 * @see DBDataObject::selectFields
944 * @param array|string|null $fields
945 * @param array $conditions
946 * @param array $options
947 * @param boolean $collapse Set to false to always return each result row as associative array.
949 * @return mixed|array|bool False on failure
951 public static function selectFieldsRow( $fields = null, array $conditions = array(), array $options = array(), $collapse = true ) {
952 $options['LIMIT'] = 1;
954 $objects = static::selectFields( $fields, $conditions, $options, $collapse );
956 return count( $objects ) > 0 ?
$objects[0] : false;
960 * Returns if there is at least one record matching the provided conditions.
961 * Condition field names get prefixed.
965 * @param array $conditions
969 public static function has( array $conditions = array() ) {
970 return static::selectRow( array( 'id' ), $conditions ) !== false;
974 * Returns the amount of matching records.
975 * Condition field names get prefixed.
979 * @param array $conditions
980 * @param array $options
984 public static function count( array $conditions = array(), array $options = array() ) {
985 $res = static::rawSelectRow(
986 array( 'COUNT(*) AS rowcount' ),
987 static::getPrefixedValues( $conditions ),
991 return $res->rowcount
;
995 * Selects the the specified fields of the records matching the provided
996 * conditions. Field names do NOT get prefixed.
1000 * @param array $fields
1001 * @param array $conditions
1002 * @param array $options
1004 * @return ResultWrapper
1006 protected static function rawSelectRow( array $fields, array $conditions = array(), array $options = array() ) {
1007 $dbr = wfGetDB( static::getReadDb() );
1009 return $dbr->selectRow(
1010 static::getDBTable(),
1019 * Update the records matching the provided conditions by
1020 * setting the fields that are keys in the $values param to
1021 * their corresponding values.
1025 * @param array $values
1026 * @param array $conditions
1028 * @return boolean Success indicator
1030 public static function update( array $values, array $conditions = array() ) {
1031 $dbw = wfGetDB( DB_MASTER
);
1033 return $dbw->update(
1034 static::getDBTable(),
1035 static::getPrefixedValues( $values ),
1036 static::getPrefixedValues( $conditions ),
1042 * Return the names of the fields.
1048 public static function getFieldNames() {
1049 return array_keys( static::getFieldTypes() );
1053 * Returns an array with the fields and their descriptions.
1055 * field name => field description
1061 public static function getFieldDescriptions() {
1066 * Get API parameters for the fields supported by this object.
1070 * @param boolean $requireParams
1071 * @param boolean $setDefaults
1075 public static function getAPIParams( $requireParams = false, $setDefaults = false ) {
1081 'bool' => 'integer',
1082 'array' => 'string',
1087 $defaults = static::getDefaults();
1089 foreach ( static::getFieldTypes() as $field => $type ) {
1090 if ( $field == 'id' ) {
1094 $hasDefault = array_key_exists( $field, $defaults );
1096 $params[$field] = array(
1097 ApiBase
::PARAM_TYPE
=> $typeMap[$type],
1098 ApiBase
::PARAM_REQUIRED
=> $requireParams && !$hasDefault
1101 if ( $type == 'array' ) {
1102 $params[$field][ApiBase
::PARAM_ISMULTI
] = true;
1105 if ( $setDefaults && $hasDefault ) {
1106 $default = is_array( $defaults[$field] ) ?
implode( '|', $defaults[$field] ) : $defaults[$field];
1107 $params[$field][ApiBase
::PARAM_DFLT
] = $default;
1115 * Computes and updates the values of the summary fields.
1119 * @param array|string|null $summaryFields
1121 public function loadSummaryFields( $summaryFields = null ) {
1126 * Computes the values of the summary fields of the objects matching the provided conditions.
1130 * @param array|string|null $summaryFields
1131 * @param array $conditions
1133 public static function updateSummaryFields( $summaryFields = null, array $conditions = array() ) {
1134 self
::setReadDb( DB_MASTER
);
1136 foreach ( self
::select( null, $conditions ) as /* DBDataObject */ $item ) {
1137 $item->loadSummaryFields( $summaryFields );
1138 $item->setSummaryMode( true );
1139 $item->saveExisting();
1142 self
::setReadDb( DB_SLAVE
);
1146 * Sets the value for the @see $updateSummaries field.
1150 * @param boolean $update
1152 public function setUpdateSummaries( $update ) {
1153 $this->updateSummaries
= $update;
1157 * Sets the value for the @see $inSummaryMode field.
1161 * @param boolean $summaryMode
1163 public function setSummaryMode( $summaryMode ) {
1164 $this->inSummaryMode
= $summaryMode;
1168 * Return if any fields got changed.
1172 * @param DBDataObject $object
1173 * @param boolean $excludeSummaryFields When set to true, summary field changes are ignored.
1177 protected function fieldsChanged( DBDataObject
$object, $excludeSummaryFields = false ) {
1178 foreach ( $this->fields
as $name => $value ) {
1179 $excluded = $excludeSummaryFields && in_array( $name, $this->getSummaryFields() );
1181 if ( !$excluded && $object->getField( $name ) !== $value ) {