Refactor deferrable updates into classes & interfaces, also add helper method for...
[lhc/web/wiklou.git] / includes / DeferredUpdates.php
1 <?php
2 /**
3 * Interface that deferrable updates should implement. Basically required so we
4 * can validate input on DeferredUpdates::addUpdate()
5 */
6 interface DeferrableUpdate {
7 /**
8 * Perform the actual work
9 */
10 function doUpdate();
11 }
12
13 /**
14 * Class for mananging the deferred updates.
15 */
16 class DeferredUpdates {
17 /**
18 * Store of updates to be deferred until the end of the request.
19 */
20 private static $updates = array();
21
22 /**
23 * Add an update to the deferred list
24 * @param $update DeferrableUpdate Some object that implements doUpdate()
25 */
26 public static function addUpdate( DeferrableUpdate $update ) {
27 array_push( self::$updates, $update );
28 }
29
30 /**
31 * HTMLCacheUpdates are the most common deferred update people use. This
32 * is a shortcut method for that.
33 * @see HTMLCacheUpdate::__construct()
34 */
35 public static function addHTMLCacheUpdate( $title, $table ) {
36 self::addUpdate( new HTMLCacheUpdate( $title, $table ) );
37 }
38
39 /**
40 * Do any deferred updates and clear the list
41 *
42 * @param $commit String: set to 'commit' to commit after every update to
43 * prevent lock contention
44 */
45 public static function doUpdates( $commit = '' ) {
46 global $wgDeferredUpdateList;
47
48 wfProfileIn( __METHOD__ );
49
50 $updates = array_merge( $wgDeferredUpdateList, self::$updates );
51
52 // No need to get master connections in case of empty updates array
53 if ( !count( $updates ) ) {
54 wfProfileOut( __METHOD__ );
55 return;
56 }
57
58 $doCommit = $commit == 'commit';
59 if ( $doCommit ) {
60 $dbw = wfGetDB( DB_MASTER );
61 }
62
63 foreach ( $updates as $update ) {
64 $update->doUpdate();
65
66 if ( $doCommit && $dbw->trxLevel() ) {
67 $dbw->commit();
68 }
69 }
70
71 self::clearPendingUpdates();
72 wfProfileOut( __METHOD__ );
73 }
74
75 /**
76 * Clear all pending updates without performing them. Generally, you don't
77 * want or need to call this. Unit tests need it though.
78 */
79 public static function clearPendingUpdates() {
80 global $wgDeferredUpdateList;
81 $wgDeferredUpdateList = self::$updates = array();
82 }
83 }