Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like LBFactory often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use LBFactory, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
31 | abstract class LBFactory implements ILBFactory { |
||
32 | /** @var ChronologyProtector */ |
||
33 | protected $chronProt; |
||
34 | /** @var object|string Class name or object With profileIn/profileOut methods */ |
||
35 | protected $profiler; |
||
36 | /** @var TransactionProfiler */ |
||
37 | protected $trxProfiler; |
||
38 | /** @var LoggerInterface */ |
||
39 | protected $replLogger; |
||
40 | /** @var LoggerInterface */ |
||
41 | protected $connLogger; |
||
42 | /** @var LoggerInterface */ |
||
43 | protected $queryLogger; |
||
44 | /** @var LoggerInterface */ |
||
45 | protected $perfLogger; |
||
46 | /** @var callable Error logger */ |
||
47 | protected $errorLogger; |
||
48 | /** @var BagOStuff */ |
||
49 | protected $srvCache; |
||
50 | /** @var BagOStuff */ |
||
51 | protected $memCache; |
||
52 | /** @var WANObjectCache */ |
||
53 | protected $wanCache; |
||
54 | |||
55 | /** @var DatabaseDomain Local domain */ |
||
56 | protected $localDomain; |
||
57 | /** @var string Local hostname of the app server */ |
||
58 | protected $hostname; |
||
59 | /** @var array Web request information about the client */ |
||
60 | protected $requestInfo; |
||
61 | |||
62 | /** @var mixed */ |
||
63 | protected $ticket; |
||
64 | /** @var string|bool String if a requested DBO_TRX transaction round is active */ |
||
65 | protected $trxRoundId = false; |
||
66 | /** @var string|bool Reason all LBs are read-only or false if not */ |
||
67 | protected $readOnlyReason = false; |
||
68 | /** @var callable[] */ |
||
69 | protected $replicationWaitCallbacks = []; |
||
70 | |||
71 | /** @var bool Whether this PHP instance is for a CLI script */ |
||
72 | protected $cliMode; |
||
73 | /** @var string Agent name for query profiling */ |
||
74 | protected $agent; |
||
75 | |||
76 | private static $loggerFields = |
||
77 | [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ]; |
||
78 | |||
79 | public function __construct( array $conf ) { |
||
80 | $this->localDomain = isset( $conf['localDomain'] ) |
||
81 | ? DatabaseDomain::newFromId( $conf['localDomain'] ) |
||
82 | : DatabaseDomain::newUnspecified(); |
||
83 | |||
84 | View Code Duplication | if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) { |
|
85 | $this->readOnlyReason = $conf['readOnlyReason']; |
||
86 | } |
||
87 | |||
88 | $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff(); |
||
89 | $this->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : new EmptyBagOStuff(); |
||
90 | $this->wanCache = isset( $conf['wanCache'] ) |
||
91 | ? $conf['wanCache'] |
||
92 | : WANObjectCache::newEmpty(); |
||
93 | |||
94 | foreach ( self::$loggerFields as $key ) { |
||
95 | $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger(); |
||
96 | } |
||
97 | $this->errorLogger = isset( $conf['errorLogger'] ) |
||
98 | ? $conf['errorLogger'] |
||
99 | : function ( Exception $e ) { |
||
100 | trigger_error( E_USER_WARNING, get_class( $e ) . ': ' . $e->getMessage() ); |
||
101 | }; |
||
102 | |||
103 | $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null; |
||
104 | $this->trxProfiler = isset( $conf['trxProfiler'] ) |
||
105 | ? $conf['trxProfiler'] |
||
106 | : new TransactionProfiler(); |
||
107 | |||
108 | $this->requestInfo = [ |
||
109 | 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '', |
||
110 | 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '', |
||
111 | 'ChronologyProtection' => 'true' |
||
112 | ]; |
||
113 | |||
114 | $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli'; |
||
115 | $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname(); |
||
116 | $this->agent = isset( $params['agent'] ) ? $params['agent'] : ''; |
||
117 | |||
118 | $this->ticket = mt_rand(); |
||
119 | } |
||
120 | |||
121 | public function destroy() { |
||
122 | $this->shutdown( self::SHUTDOWN_NO_CHRONPROT ); |
||
123 | $this->forEachLBCallMethod( 'disable' ); |
||
124 | } |
||
125 | |||
126 | public function shutdown( |
||
127 | $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null |
||
128 | ) { |
||
129 | $chronProt = $this->getChronologyProtector(); |
||
130 | if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) { |
||
131 | $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' ); |
||
132 | } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) { |
||
133 | $this->shutdownChronologyProtector( $chronProt, null, 'async' ); |
||
134 | } |
||
135 | |||
136 | $this->commitMasterChanges( __METHOD__ ); // sanity |
||
137 | } |
||
138 | |||
139 | /** |
||
140 | * @see ILBFactory::newMainLB() |
||
141 | * @param bool $domain |
||
142 | * @return LoadBalancer |
||
143 | */ |
||
144 | abstract public function newMainLB( $domain = false ); |
||
145 | |||
146 | /** |
||
147 | * @see ILBFactory::getMainLB() |
||
148 | * @param bool $domain |
||
149 | * @return LoadBalancer |
||
150 | */ |
||
151 | abstract public function getMainLB( $domain = false ); |
||
152 | |||
153 | /** |
||
154 | * @see ILBFactory::newExternalLB() |
||
155 | * @param string $cluster |
||
156 | * @return LoadBalancer |
||
157 | */ |
||
158 | abstract public function newExternalLB( $cluster ); |
||
159 | |||
160 | /** |
||
161 | * @see ILBFactory::getExternalLB() |
||
162 | * @param string $cluster |
||
163 | * @return LoadBalancer |
||
164 | */ |
||
165 | abstract public function getExternalLB( $cluster ); |
||
166 | |||
167 | /** |
||
168 | * Call a method of each tracked load balancer |
||
169 | * |
||
170 | * @param string $methodName |
||
171 | * @param array $args |
||
172 | */ |
||
173 | protected function forEachLBCallMethod( $methodName, array $args = [] ) { |
||
174 | $this->forEachLB( |
||
175 | function ( ILoadBalancer $loadBalancer, $methodName, array $args ) { |
||
176 | call_user_func_array( [ $loadBalancer, $methodName ], $args ); |
||
177 | }, |
||
178 | [ $methodName, $args ] |
||
179 | ); |
||
180 | } |
||
181 | |||
182 | public function flushReplicaSnapshots( $fname = __METHOD__ ) { |
||
183 | $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] ); |
||
184 | } |
||
185 | |||
186 | public function commitAll( $fname = __METHOD__, array $options = [] ) { |
||
187 | $this->commitMasterChanges( $fname, $options ); |
||
188 | $this->forEachLBCallMethod( 'commitAll', [ $fname ] ); |
||
189 | } |
||
190 | |||
191 | public function beginMasterChanges( $fname = __METHOD__ ) { |
||
192 | if ( $this->trxRoundId !== false ) { |
||
193 | throw new DBTransactionError( |
||
194 | null, |
||
195 | "$fname: transaction round '{$this->trxRoundId}' already started." |
||
196 | ); |
||
197 | } |
||
198 | $this->trxRoundId = $fname; |
||
199 | // Set DBO_TRX flags on all appropriate DBs |
||
200 | $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] ); |
||
201 | } |
||
202 | |||
203 | public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) { |
||
204 | if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) { |
||
205 | throw new DBTransactionError( |
||
206 | null, |
||
207 | "$fname: transaction round '{$this->trxRoundId}' still running." |
||
208 | ); |
||
209 | } |
||
210 | /** @noinspection PhpUnusedLocalVariableInspection */ |
||
211 | $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts |
||
212 | // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure |
||
213 | $this->forEachLBCallMethod( 'finalizeMasterChanges' ); |
||
214 | $this->trxRoundId = false; |
||
215 | // Perform pre-commit checks, aborting on failure |
||
216 | $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] ); |
||
217 | // Log the DBs and methods involved in multi-DB transactions |
||
218 | $this->logIfMultiDbTransaction(); |
||
219 | // Actually perform the commit on all master DB connections and revert DBO_TRX |
||
220 | $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] ); |
||
221 | // Run all post-commit callbacks |
||
222 | /** @var Exception $e */ |
||
223 | $e = null; // first callback exception |
||
224 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) { |
||
225 | $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT ); |
||
226 | $e = $e ?: $ex; |
||
227 | } ); |
||
228 | // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB |
||
229 | $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] ); |
||
230 | // Throw any last post-commit callback error |
||
231 | if ( $e instanceof Exception ) { |
||
232 | throw $e; |
||
233 | } |
||
234 | } |
||
235 | |||
236 | public function rollbackMasterChanges( $fname = __METHOD__ ) { |
||
237 | $this->trxRoundId = false; |
||
238 | $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' ); |
||
239 | $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] ); |
||
240 | // Run all post-rollback callbacks |
||
241 | $this->forEachLB( function ( ILoadBalancer $lb ) { |
||
242 | $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK ); |
||
243 | } ); |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * Log query info if multi DB transactions are going to be committed now |
||
248 | */ |
||
249 | private function logIfMultiDbTransaction() { |
||
250 | $callersByDB = []; |
||
251 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) { |
||
252 | $masterName = $lb->getServerName( $lb->getWriterIndex() ); |
||
253 | $callers = $lb->pendingMasterChangeCallers(); |
||
254 | if ( $callers ) { |
||
255 | $callersByDB[$masterName] = $callers; |
||
256 | } |
||
257 | } ); |
||
258 | |||
259 | if ( count( $callersByDB ) >= 2 ) { |
||
260 | $dbs = implode( ', ', array_keys( $callersByDB ) ); |
||
261 | $msg = "Multi-DB transaction [{$dbs}]:\n"; |
||
262 | foreach ( $callersByDB as $db => $callers ) { |
||
263 | $msg .= "$db: " . implode( '; ', $callers ) . "\n"; |
||
264 | } |
||
265 | $this->queryLogger->info( $msg ); |
||
266 | } |
||
267 | } |
||
268 | |||
269 | public function hasMasterChanges() { |
||
270 | $ret = false; |
||
271 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) { |
||
272 | $ret = $ret || $lb->hasMasterChanges(); |
||
273 | } ); |
||
274 | |||
275 | return $ret; |
||
276 | } |
||
277 | |||
278 | public function laggedReplicaUsed() { |
||
279 | $ret = false; |
||
280 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) { |
||
281 | $ret = $ret || $lb->laggedReplicaUsed(); |
||
282 | } ); |
||
283 | |||
284 | return $ret; |
||
285 | } |
||
286 | |||
287 | public function hasOrMadeRecentMasterChanges( $age = null ) { |
||
288 | $ret = false; |
||
289 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) { |
||
290 | $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age ); |
||
291 | } ); |
||
292 | return $ret; |
||
293 | } |
||
294 | |||
295 | public function waitForReplication( array $opts = [] ) { |
||
296 | $opts += [ |
||
297 | 'domain' => false, |
||
298 | 'cluster' => false, |
||
299 | 'timeout' => 60, |
||
300 | 'ifWritesSince' => null |
||
301 | ]; |
||
302 | |||
303 | if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) { |
||
304 | $opts['domain'] = $opts['wiki']; // b/c |
||
305 | } |
||
306 | |||
307 | // Figure out which clusters need to be checked |
||
308 | /** @var ILoadBalancer[] $lbs */ |
||
309 | $lbs = []; |
||
310 | if ( $opts['cluster'] !== false ) { |
||
311 | $lbs[] = $this->getExternalLB( $opts['cluster'] ); |
||
312 | } elseif ( $opts['domain'] !== false ) { |
||
313 | $lbs[] = $this->getMainLB( $opts['domain'] ); |
||
314 | } else { |
||
315 | $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) { |
||
316 | $lbs[] = $lb; |
||
317 | } ); |
||
318 | if ( !$lbs ) { |
||
319 | return; // nothing actually used |
||
320 | } |
||
321 | } |
||
322 | |||
323 | // Get all the master positions of applicable DBs right now. |
||
324 | // This can be faster since waiting on one cluster reduces the |
||
325 | // time needed to wait on the next clusters. |
||
326 | $masterPositions = array_fill( 0, count( $lbs ), false ); |
||
327 | foreach ( $lbs as $i => $lb ) { |
||
328 | if ( $lb->getServerCount() <= 1 ) { |
||
329 | // Bug 27975 - Don't try to wait for replica DBs if there are none |
||
330 | // Prevents permission error when getting master position |
||
331 | continue; |
||
332 | } elseif ( $opts['ifWritesSince'] |
||
333 | && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince'] |
||
334 | ) { |
||
335 | continue; // no writes since the last wait |
||
336 | } |
||
337 | $masterPositions[$i] = $lb->getMasterPos(); |
||
338 | } |
||
339 | |||
340 | // Run any listener callbacks *after* getting the DB positions. The more |
||
341 | // time spent in the callbacks, the less time is spent in waitForAll(). |
||
342 | foreach ( $this->replicationWaitCallbacks as $callback ) { |
||
343 | $callback(); |
||
344 | } |
||
345 | |||
346 | $failed = []; |
||
347 | foreach ( $lbs as $i => $lb ) { |
||
348 | if ( $masterPositions[$i] ) { |
||
349 | // The DBMS may not support getMasterPos() |
||
350 | if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) { |
||
351 | $failed[] = $lb->getServerName( $lb->getWriterIndex() ); |
||
352 | } |
||
353 | } |
||
354 | } |
||
355 | |||
356 | if ( $failed ) { |
||
357 | throw new DBReplicationWaitError( |
||
358 | null, |
||
359 | "Could not wait for replica DBs to catch up to " . |
||
360 | implode( ', ', $failed ) |
||
361 | ); |
||
362 | } |
||
363 | } |
||
364 | |||
365 | public function setWaitForReplicationListener( $name, callable $callback = null ) { |
||
372 | |||
373 | public function getEmptyTransactionTicket( $fname ) { |
||
383 | |||
384 | public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) { |
||
409 | |||
410 | public function getChronologyProtectorTouched( $dbName ) { |
||
413 | |||
414 | public function disableChronologyProtection() { |
||
417 | |||
418 | /** |
||
419 | * @return ChronologyProtector |
||
420 | */ |
||
421 | protected function getChronologyProtector() { |
||
449 | |||
450 | /** |
||
451 | * Get and record all of the staged DB positions into persistent memory storage |
||
452 | * |
||
453 | * @param ChronologyProtector $cp |
||
454 | * @param callable|null $workCallback Work to do instead of waiting on syncing positions |
||
455 | * @param string $mode One of (sync, async); whether to wait on remote datacenters |
||
456 | */ |
||
457 | protected function shutdownChronologyProtector( |
||
482 | |||
483 | /** |
||
484 | * Base parameters to LoadBalancer::__construct() |
||
485 | * @return array |
||
486 | */ |
||
487 | final protected function baseLoadBalancerParams() { |
||
504 | |||
505 | /** |
||
506 | * @param ILoadBalancer $lb |
||
507 | */ |
||
508 | protected function initLoadBalancer( ILoadBalancer $lb ) { |
||
513 | |||
514 | public function setDomainPrefix( $prefix ) { |
||
525 | |||
526 | public function closeAll() { |
||
529 | |||
530 | public function setAgentName( $agent ) { |
||
533 | |||
534 | public function appendPreShutdownTimeAsQuery( $url, $time ) { |
||
546 | |||
547 | public function setRequestInfo( array $info ) { |
||
550 | |||
551 | /** |
||
552 | * Make PHP ignore user aborts/disconnects until the returned |
||
553 | * value leaves scope. This returns null and does nothing in CLI mode. |
||
554 | * |
||
555 | * @return ScopedCallback|null |
||
556 | */ |
||
557 | View Code Duplication | final protected function getScopedPHPBehaviorForCommit() { |
|
567 | |||
568 | function __destruct() { |
||
571 | } |
||
572 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: