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
23 * These methods are likely candidates for overriding:
31 * Main instance methods:
37 * Main static methods:
51 * @licence GNU GPL v2 or later
52 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
55 abstract class ORMRow
{
58 * The fields of the object.
59 * field name (w/o prefix) => value
64 protected $fields = array( 'id' => null );
73 * If the object should update summaries of linked items when changed.
74 * For example, update the course_count field in universities when a course in courses is deleted.
75 * Settings this to false can prevent needless updating work in situations
76 * such as deleting a university, which will then delete all it's courses.
81 protected $updateSummaries = true;
84 * Indicates if the object is in summary mode.
85 * This mode indicates that only summary fields got updated,
86 * which allows for optimizations.
91 protected $inSummaryMode = false;
98 * @param ORMTable $table
99 * @param array|null $fields
100 * @param boolean $loadDefaults
102 public function __construct( ORMTable
$table, $fields = null, $loadDefaults = false ) {
103 $this->table
= $table;
105 if ( !is_array( $fields ) ) {
109 if ( $loadDefaults ) {
110 $fields = array_merge( $this->table
->getDefaults(), $fields );
113 $this->setFields( $fields );
117 * Load the specified fields from the database.
121 * @param array|null $fields
122 * @param boolean $override
123 * @param boolean $skipLoaded
125 * @return bool Success indicator
127 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
128 if ( is_null( $this->getId() ) ) {
132 if ( is_null( $fields ) ) {
133 $fields = array_keys( $this->table
->getFields() );
137 $fields = array_diff( $fields, array_keys( $this->fields
) );
140 if ( !empty( $fields ) ) {
141 $result = $this->table
->rawSelectRow(
142 $this->table
->getPrefixedFields( $fields ),
143 array( $this->table
->getPrefixedField( 'id' ) => $this->getId() ),
144 array( 'LIMIT' => 1 )
147 if ( $result !== false ) {
148 $this->setFields( $this->table
->getFieldsFromDBResult( $result ), $override );
158 * Gets the value of a field.
162 * @param string $name
163 * @param mixed $default
165 * @throws MWException
168 public function getField( $name, $default = null ) {
169 if ( $this->hasField( $name ) ) {
170 return $this->fields
[$name];
171 } elseif ( !is_null( $default ) ) {
174 throw new MWException( 'Attempted to get not-set field ' . $name );
179 * Gets the value of a field but first loads it if not done so already.
187 public function loadAndGetField( $name ) {
188 if ( !$this->hasField( $name ) ) {
189 $this->loadFields( array( $name ) );
192 return $this->getField( $name );
200 * @param string $name
202 public function removeField( $name ) {
203 unset( $this->fields
[$name] );
207 * Returns the objects database id.
211 * @return integer|null
213 public function getId() {
214 return $this->getField( 'id' );
218 * Sets the objects database id.
222 * @param integer|null $id
224 public function setId( $id ) {
225 $this->setField( 'id', $id );
229 * Gets if a certain field is set.
233 * @param string $name
237 public function hasField( $name ) {
238 return array_key_exists( $name, $this->fields
);
242 * Gets if the id field is set.
248 public function hasIdField() {
249 return $this->hasField( 'id' )
250 && !is_null( $this->getField( 'id' ) );
254 * Sets multiple fields.
258 * @param array $fields The fields to set
259 * @param boolean $override Override already set fields with the provided values?
261 public function setFields( array $fields, $override = true ) {
262 foreach ( $fields as $name => $value ) {
263 if ( $override ||
!$this->hasField( $name ) ) {
264 $this->setField( $name, $value );
270 * Gets the fields => values to write to the table.
276 protected function getWriteValues() {
279 foreach ( $this->table
->getFields() as $name => $type ) {
280 if ( array_key_exists( $name, $this->fields
) ) {
281 $value = $this->fields
[$name];
285 $value = (array)$value;
287 $value = serialize( $value );
290 $values[$this->table
->getPrefixedField( $name )] = $value;
298 * Serializes the object to an associative array which
299 * can then easily be converted into JSON or similar.
303 * @param null|array $fields
304 * @param boolean $incNullId
308 public function toArray( $fields = null, $incNullId = false ) {
310 $setFields = array();
312 if ( !is_array( $fields ) ) {
313 $setFields = $this->getSetFieldNames();
315 foreach ( $fields as $field ) {
316 if ( $this->hasField( $field ) ) {
317 $setFields[] = $field;
322 foreach ( $setFields as $field ) {
323 if ( $incNullId ||
$field != 'id' ||
$this->hasIdField() ) {
324 $data[$field] = $this->getField( $field );
332 * Load the default values, via getDefaults.
336 * @param boolean $override
338 public function loadDefaults( $override = true ) {
339 $this->setFields( $this->table
->getDefaults(), $override );
343 * Writes the answer to the database, either updating it
344 * when it already exists, or inserting it when it doesn't.
348 * @param string|null $functionName
350 * @return boolean Success indicator
352 public function save( $functionName = null ) {
353 if ( $this->hasIdField() ) {
354 return $this->saveExisting( $functionName );
356 return $this->insert( $functionName );
361 * Updates the object in the database.
365 * @param string|null $functionName
367 * @return boolean Success indicator
369 protected function saveExisting( $functionName = null ) {
370 $dbw = wfGetDB( DB_MASTER
);
372 $success = $dbw->update(
373 $this->table
->getName(),
374 $this->getWriteValues(),
375 $this->table
->getPrefixedValues( $this->getUpdateConditions() ),
376 is_null( $functionName ) ? __METHOD__
: $functionName
383 * Returns the WHERE considtions needed to identify this object so
390 protected function getUpdateConditions() {
391 return array( 'id' => $this->getId() );
395 * Inserts the object into the database.
399 * @param string|null $functionName
400 * @param array|null $options
402 * @return boolean Success indicator
404 protected function insert( $functionName = null, array $options = null ) {
405 $dbw = wfGetDB( DB_MASTER
);
407 $result = $dbw->insert(
408 $this->table
->getName(),
409 $this->getWriteValues(),
410 is_null( $functionName ) ? __METHOD__
: $functionName,
411 is_null( $options ) ?
array( 'IGNORE' ) : $options
415 $this->setField( 'id', $dbw->insertId() );
422 * Removes the object from the database.
426 * @return boolean Success indicator
428 public function remove() {
429 $this->beforeRemove();
431 $success = $this->table
->delete( array( 'id' => $this->getId() ) );
441 * Gets called before an object is removed from the database.
445 protected function beforeRemove() {
446 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
450 * Before removal of an object happens, @see beforeRemove gets called.
451 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
452 * This allows for loading info needed after removal to get rid of linked data and the like.
458 protected function getBeforeRemoveFields() {
463 * Gets called after successfull removal.
464 * Can be overriden to get rid of linked data.
468 protected function onRemoved() {
469 $this->setField( 'id', null );
473 * Return the names and values of the fields.
479 public function getFields() {
480 return $this->fields
;
484 * Return the names of the fields.
490 public function getSetFieldNames() {
491 return array_keys( $this->fields
);
495 * Sets the value of a field.
496 * Strings can be provided for other types,
497 * so this method can be called from unserialization handlers.
501 * @param string $name
502 * @param mixed $value
504 * @throws MWException
506 public function setField( $name, $value ) {
507 $fields = $this->table
->getFields();
509 if ( array_key_exists( $name, $fields ) ) {
510 switch ( $fields[$name] ) {
512 $value = (int)$value;
515 $value = (float)$value;
518 if ( is_string( $value ) ) {
519 $value = $value !== '0';
520 } elseif ( is_int( $value ) ) {
521 $value = $value !== 0;
525 if ( is_string( $value ) ) {
526 $value = unserialize( $value );
529 if ( !is_array( $value ) ) {
534 if ( is_string( $value ) ) {
535 $value = unserialize( $value );
539 if ( is_string( $value ) ) {
540 $value = (int)$value;
545 $this->fields
[$name] = $value;
547 throw new MWException( 'Attempted to set unknown field ' . $name );
552 * Add an amount (can be negative) to the specified field (needs to be numeric).
556 * @param string $field
557 * @param integer $amount
559 * @return boolean Success indicator
561 public function addToField( $field, $amount ) {
562 if ( $amount == 0 ) {
566 if ( !$this->hasIdField() ) {
570 $absoluteAmount = abs( $amount );
571 $isNegative = $amount < 0;
573 $dbw = wfGetDB( DB_MASTER
);
575 $fullField = $this->table
->getPrefixedField( $field );
577 $success = $dbw->update(
578 $this->table
->getName(),
579 array( "$fullField=$fullField" . ( $isNegative ?
'-' : '+' ) . $absoluteAmount ),
580 array( $this->table
->getPrefixedField( 'id' ) => $this->getId() ),
584 if ( $success && $this->hasField( $field ) ) {
585 $this->setField( $field, $this->getField( $field ) +
$amount );
592 * Return the names of the fields.
598 public function getFieldNames() {
599 return array_keys( $this->table
->getFields() );
603 * Computes and updates the values of the summary fields.
607 * @param array|string|null $summaryFields
609 public function loadSummaryFields( $summaryFields = null ) {
614 * Sets the value for the @see $updateSummaries field.
618 * @param boolean $update
620 public function setUpdateSummaries( $update ) {
621 $this->updateSummaries
= $update;
625 * Sets the value for the @see $inSummaryMode field.
629 * @param boolean $summaryMode
631 public function setSummaryMode( $summaryMode ) {
632 $this->inSummaryMode
= $summaryMode;
636 * Return if any fields got changed.
640 * @param ORMRow $object
641 * @param boolean|array $excludeSummaryFields
642 * When set to true, summary field changes are ignored.
643 * Can also be an array of fields to ignore.
647 protected function fieldsChanged( ORMRow
$object, $excludeSummaryFields = false ) {
648 $exclusionFields = array();
650 if ( $excludeSummaryFields !== false ) {
651 $exclusionFields = is_array( $excludeSummaryFields ) ?
$excludeSummaryFields : $this->table
->getSummaryFields();
654 foreach ( $this->fields
as $name => $value ) {
655 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
657 if ( !$excluded && $object->getField( $name ) !== $value ) {
666 * Returns the table this ORMRow is a row in.
672 public function getTable() {