3 * Abstract base class for representing objects that are stored in some DB table.
4 * This is basically an ORM-like wrapper around rows in database tables that
5 * aims to be both simple and very flexible. It is centered around an associative
6 * array of fields and various methods to do common interaction with the database.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * @licence GNU GPL v2 or later
29 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
32 abstract class ORMRow
implements IORMRow
{
35 * The fields of the object.
36 * field name (w/o prefix) => value
41 protected $fields = array( 'id' => null );
50 * If the object should update summaries of linked items when changed.
51 * For example, update the course_count field in universities when a course in courses is deleted.
52 * Settings this to false can prevent needless updating work in situations
53 * such as deleting a university, which will then delete all it's courses.
58 protected $updateSummaries = true;
61 * Indicates if the object is in summary mode.
62 * This mode indicates that only summary fields got updated,
63 * which allows for optimizations.
68 protected $inSummaryMode = false;
75 * @param IORMTable $table
76 * @param array|null $fields
77 * @param boolean $loadDefaults
79 public function __construct( IORMTable
$table, $fields = null, $loadDefaults = false ) {
80 $this->table
= $table;
82 if ( !is_array( $fields ) ) {
86 if ( $loadDefaults ) {
87 $fields = array_merge( $this->table
->getDefaults(), $fields );
90 $this->setFields( $fields );
94 * Load the specified fields from the database.
98 * @param array|null $fields
99 * @param boolean $override
100 * @param boolean $skipLoaded
102 * @return bool Success indicator
104 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
105 if ( is_null( $this->getId() ) ) {
109 if ( is_null( $fields ) ) {
110 $fields = array_keys( $this->table
->getFields() );
114 $fields = array_diff( $fields, array_keys( $this->fields
) );
117 if ( !empty( $fields ) ) {
118 $result = $this->table
->rawSelectRow(
119 $this->table
->getPrefixedFields( $fields ),
120 array( $this->table
->getPrefixedField( 'id' ) => $this->getId() ),
121 array( 'LIMIT' => 1 )
124 if ( $result !== false ) {
125 $this->setFields( $this->table
->getFieldsFromDBResult( $result ), $override );
135 * Gets the value of a field.
139 * @param string $name
140 * @param mixed $default
142 * @throws MWException
145 public function getField( $name, $default = null ) {
146 if ( $this->hasField( $name ) ) {
147 return $this->fields
[$name];
148 } elseif ( !is_null( $default ) ) {
151 throw new MWException( 'Attempted to get not-set field ' . $name );
156 * Gets the value of a field but first loads it if not done so already.
164 public function loadAndGetField( $name ) {
165 if ( !$this->hasField( $name ) ) {
166 $this->loadFields( array( $name ) );
169 return $this->getField( $name );
177 * @param string $name
179 public function removeField( $name ) {
180 unset( $this->fields
[$name] );
184 * Returns the objects database id.
188 * @return integer|null
190 public function getId() {
191 return $this->getField( 'id' );
195 * Sets the objects database id.
199 * @param integer|null $id
201 public function setId( $id ) {
202 $this->setField( 'id', $id );
206 * Gets if a certain field is set.
210 * @param string $name
214 public function hasField( $name ) {
215 return array_key_exists( $name, $this->fields
);
219 * Gets if the id field is set.
225 public function hasIdField() {
226 return $this->hasField( 'id' )
227 && !is_null( $this->getField( 'id' ) );
231 * Sets multiple fields.
235 * @param array $fields The fields to set
236 * @param boolean $override Override already set fields with the provided values?
238 public function setFields( array $fields, $override = true ) {
239 foreach ( $fields as $name => $value ) {
240 if ( $override ||
!$this->hasField( $name ) ) {
241 $this->setField( $name, $value );
247 * Gets the fields => values to write to the table.
253 protected function getWriteValues() {
256 foreach ( $this->table
->getFields() as $name => $type ) {
257 if ( array_key_exists( $name, $this->fields
) ) {
258 $value = $this->fields
[$name];
262 $value = (array)$value;
264 $value = serialize( $value );
267 $values[$this->table
->getPrefixedField( $name )] = $value;
275 * Serializes the object to an associative array which
276 * can then easily be converted into JSON or similar.
280 * @param null|array $fields
281 * @param boolean $incNullId
285 public function toArray( $fields = null, $incNullId = false ) {
287 $setFields = array();
289 if ( !is_array( $fields ) ) {
290 $setFields = $this->getSetFieldNames();
292 foreach ( $fields as $field ) {
293 if ( $this->hasField( $field ) ) {
294 $setFields[] = $field;
299 foreach ( $setFields as $field ) {
300 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
301 $data[$field] = $this->getField( $field );
309 * Load the default values, via getDefaults.
313 * @param boolean $override
315 public function loadDefaults( $override = true ) {
316 $this->setFields( $this->table
->getDefaults(), $override );
320 * Writes the answer to the database, either updating it
321 * when it already exists, or inserting it when it doesn't.
325 * @param string|null $functionName
327 * @return boolean Success indicator
329 public function save( $functionName = null ) {
330 if ( $this->hasIdField() ) {
331 return $this->saveExisting( $functionName );
333 return $this->insert( $functionName );
338 * Updates the object in the database.
342 * @param string|null $functionName
344 * @return boolean Success indicator
346 protected function saveExisting( $functionName = null ) {
347 $dbw = wfGetDB( DB_MASTER
);
349 $success = $dbw->update(
350 $this->table
->getName(),
351 $this->getWriteValues(),
352 $this->table
->getPrefixedValues( $this->getUpdateConditions() ),
353 is_null( $functionName ) ? __METHOD__
: $functionName
360 * Returns the WHERE considtions needed to identify this object so
367 protected function getUpdateConditions() {
368 return array( 'id' => $this->getId() );
372 * Inserts the object into the database.
376 * @param string|null $functionName
377 * @param array|null $options
379 * @return boolean Success indicator
381 protected function insert( $functionName = null, array $options = null ) {
382 $dbw = wfGetDB( DB_MASTER
);
384 $result = $dbw->insert(
385 $this->table
->getName(),
386 $this->getWriteValues(),
387 is_null( $functionName ) ? __METHOD__
: $functionName,
388 is_null( $options ) ?
array( 'IGNORE' ) : $options
392 $this->setField( 'id', $dbw->insertId() );
399 * Removes the object from the database.
403 * @return boolean Success indicator
405 public function remove() {
406 $this->beforeRemove();
408 $success = $this->table
->delete( array( 'id' => $this->getId() ) );
418 * Gets called before an object is removed from the database.
422 protected function beforeRemove() {
423 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
427 * Before removal of an object happens, @see beforeRemove gets called.
428 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
429 * This allows for loading info needed after removal to get rid of linked data and the like.
435 protected function getBeforeRemoveFields() {
440 * Gets called after successfull removal.
441 * Can be overriden to get rid of linked data.
445 protected function onRemoved() {
446 $this->setField( 'id', null );
450 * Return the names and values of the fields.
456 public function getFields() {
457 return $this->fields
;
461 * Return the names of the fields.
467 public function getSetFieldNames() {
468 return array_keys( $this->fields
);
472 * Sets the value of a field.
473 * Strings can be provided for other types,
474 * so this method can be called from unserialization handlers.
478 * @param string $name
479 * @param mixed $value
481 * @throws MWException
483 public function setField( $name, $value ) {
484 $fields = $this->table
->getFields();
486 if ( array_key_exists( $name, $fields ) ) {
487 switch ( $fields[$name] ) {
489 $value = (int)$value;
492 $value = (float)$value;
495 if ( is_string( $value ) ) {
496 $value = $value !== '0';
497 } elseif ( is_int( $value ) ) {
498 $value = $value !== 0;
502 if ( is_string( $value ) ) {
503 $value = unserialize( $value );
506 if ( !is_array( $value ) ) {
511 if ( is_string( $value ) ) {
512 $value = unserialize( $value );
516 if ( is_string( $value ) ) {
517 $value = (int)$value;
522 $this->fields
[$name] = $value;
524 throw new MWException( 'Attempted to set unknown field ' . $name );
529 * Add an amount (can be negative) to the specified field (needs to be numeric).
530 * TODO: most off this stuff makes more sense in the table class
534 * @param string $field
535 * @param integer $amount
537 * @return boolean Success indicator
539 public function addToField( $field, $amount ) {
540 if ( $amount == 0 ) {
544 if ( !$this->hasIdField() ) {
548 $absoluteAmount = abs( $amount );
549 $isNegative = $amount < 0;
551 $dbw = wfGetDB( DB_MASTER
);
553 $fullField = $this->table
->getPrefixedField( $field );
555 $success = $dbw->update(
556 $this->table
->getName(),
557 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
558 array( $this->table
->getPrefixedField( 'id' ) => $this->getId() ),
562 if ( $success && $this->hasField( $field ) ) {
563 $this->setField( $field, $this->getField( $field ) +
$amount );
570 * Return the names of the fields.
576 public function getFieldNames() {
577 return array_keys( $this->table
->getFields() );
581 * Computes and updates the values of the summary fields.
585 * @param array|string|null $summaryFields
587 public function loadSummaryFields( $summaryFields = null ) {
592 * Sets the value for the @see $updateSummaries field.
596 * @param boolean $update
598 public function setUpdateSummaries( $update ) {
599 $this->updateSummaries
= $update;
603 * Sets the value for the @see $inSummaryMode field.
607 * @param boolean $summaryMode
609 public function setSummaryMode( $summaryMode ) {
610 $this->inSummaryMode
= $summaryMode;
614 * Return if any fields got changed.
618 * @param IORMRow $object
619 * @param boolean|array $excludeSummaryFields
620 * When set to true, summary field changes are ignored.
621 * Can also be an array of fields to ignore.
625 protected function fieldsChanged( IORMRow
$object, $excludeSummaryFields = false ) {
626 $exclusionFields = array();
628 if ( $excludeSummaryFields !== false ) {
629 $exclusionFields = is_array( $excludeSummaryFields ) ?
$excludeSummaryFields : $this->table
->getSummaryFields();
632 foreach ( $this->fields
as $name => $value ) {
633 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
635 if ( !$excluded && $object->getField( $name ) !== $value ) {
644 * Returns the table this IORMRow is a row in.
650 public function getTable() {