Make GenderCache use MediaWikiServices
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use Config;
5 use ConfigFactory;
6 use EventRelayerGroup;
7 use GenderCache;
8 use GlobalVarConfig;
9 use Hooks;
10 use LBFactory;
11 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
12 use LoadBalancer;
13 use MediaWiki\Services\ServiceContainer;
14 use MWException;
15 use ResourceLoader;
16 use SearchEngine;
17 use SearchEngineConfig;
18 use SearchEngineFactory;
19 use SiteLookup;
20 use SiteStore;
21 use WatchedItemStore;
22 use SkinFactory;
23
24 /**
25 * Service locator for MediaWiki core services.
26 *
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 2 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License along
38 * with this program; if not, write to the Free Software Foundation, Inc.,
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
40 * http://www.gnu.org/copyleft/gpl.html
41 *
42 * @file
43 *
44 * @since 1.27
45 */
46
47 /**
48 * MediaWikiServices is the service locator for the application scope of MediaWiki.
49 * Its implemented as a simple configurable DI container.
50 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
51 * the network of service objects that defines MediaWiki's application logic.
52 * It acts as an entry point to MediaWiki's dependency injection mechanism.
53 *
54 * Services are defined in the "wiring" array passed to the constructor,
55 * or by calling defineService().
56 *
57 * @see docs/injection.txt for an overview of using dependency injection in the
58 * MediaWiki code base.
59 */
60 class MediaWikiServices extends ServiceContainer {
61
62 /**
63 * @var MediaWikiServices|null
64 */
65 private static $instance = null;
66
67 /**
68 * Returns the global default instance of the top level service locator.
69 *
70 * The default instance is initialized using the service instantiator functions
71 * defined in ServiceWiring.php.
72 *
73 * @note This should only be called by static functions! The instance returned here
74 * should not be passed around! Objects that need access to a service should have
75 * that service injected into the constructor, never a service locator!
76 *
77 * @return MediaWikiServices
78 */
79 public static function getInstance() {
80 if ( self::$instance === null ) {
81 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
82 // but some information from the global scope has to be injected here,
83 // even if it's just a file name or database credentials to load
84 // configuration from.
85 $bootstrapConfig = new GlobalVarConfig();
86 self::$instance = self::newInstance( $bootstrapConfig );
87 }
88
89 return self::$instance;
90 }
91
92 /**
93 * Replaces the global MediaWikiServices instance.
94 *
95 * @note This is for use in PHPUnit tests only!
96 *
97 * @throws MWException if called outside of PHPUnit tests.
98 *
99 * @param MediaWikiServices $services The new MediaWikiServices object.
100 *
101 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
102 */
103 public static function forceGlobalInstance( MediaWikiServices $services ) {
104 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
105 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
106 }
107
108 $old = self::getInstance();
109 self::$instance = $services;
110
111 return $old;
112 }
113
114 /**
115 * Creates a new instance of MediaWikiServices and sets it as the global default
116 * instance. getInstance() will return a different MediaWikiServices object
117 * after every call to resetGlobalServiceLocator().
118 *
119 * @warning This should not be used during normal operation. It is intended for use
120 * when the configuration has changed significantly since bootstrap time, e.g.
121 * during the installation process or during testing.
122 *
123 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
124 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
125 * any of the services managed by MediaWikiServices exist. If any service objects
126 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
127 * with the operation of the services managed by the new MediaWikiServices.
128 * Operating with a mix of services created by the old and the new
129 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
130 * Any class implementing LAZY LOADING is especially prone to this problem,
131 * since instances would typically retain a reference to a storage layer service.
132 *
133 * @see forceGlobalInstance()
134 * @see resetGlobalInstance()
135 * @see resetBetweenTest()
136 *
137 * @param Config|null $bootstrapConfig The Config object to be registered as the
138 * 'BootstrapConfig' service. This has to contain at least the information
139 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
140 * config of the old instance of MediaWikiServices will be re-used. If there
141 * was no previous instance, a new GlobalVarConfig object will be used to
142 * bootstrap the services.
143 *
144 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
145 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
146 * is defined).
147 */
148 public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
149 if ( self::$instance === null ) {
150 // no global instance yet, nothing to reset
151 return;
152 }
153
154 self::failIfResetNotAllowed( __METHOD__ );
155
156 if ( $bootstrapConfig === null ) {
157 $bootstrapConfig = self::$instance->getBootstrapConfig();
158 }
159
160 self::$instance->destroy();
161
162 self::$instance = self::newInstance( $bootstrapConfig );
163 }
164
165 /**
166 * Creates a new MediaWikiServices instance and initializes it according to the
167 * given $bootstrapConfig. In particular, all wiring files defined in the
168 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
169 *
170 * @param Config|null $bootstrapConfig The Config object to be registered as the
171 * 'BootstrapConfig' service. This has to contain at least the information
172 * needed to set up the 'ConfigFactory' service. If not provided, any call
173 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
174 * A MediaWikiServices instance without access to configuration is called
175 * "primordial".
176 *
177 * @return MediaWikiServices
178 * @throws MWException
179 */
180 private static function newInstance( Config $bootstrapConfig ) {
181 $instance = new self( $bootstrapConfig );
182
183 // Load the default wiring from the specified files.
184 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
185 $instance->loadWiringFiles( $wiringFiles );
186
187 // Provide a traditional hook point to allow extensions to configure services.
188 Hooks::run( 'MediaWikiServices', [ $instance ] );
189
190 return $instance;
191 }
192
193 /**
194 * Disables all storage layer services. After calling this, any attempt to access the
195 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
196 * operation.
197 *
198 * @warning This is intended for extreme situations only and should never be used
199 * while serving normal web requests. Legitimate use cases for this method include
200 * the installation process. Test fixtures may also use this, if the fixture relies
201 * on globalState.
202 *
203 * @see resetGlobalInstance()
204 * @see resetChildProcessServices()
205 */
206 public static function disableStorageBackend() {
207 // TODO: also disable some Caches, JobQueues, etc
208 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
209 $services = self::getInstance();
210
211 foreach ( $destroy as $name ) {
212 $services->disableService( $name );
213 }
214 }
215
216 /**
217 * Resets any services that may have become stale after a child process
218 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
219 * to call this method from the parent process.
220 *
221 * @note This is intended for use in the context of process forking only!
222 *
223 * @see resetGlobalInstance()
224 * @see disableStorageBackend()
225 */
226 public static function resetChildProcessServices() {
227 // NOTE: for now, just reset everything. Since we don't know the interdependencies
228 // between services, we can't do this more selectively at this time.
229 self::resetGlobalInstance();
230
231 // Child, reseed because there is no bug in PHP:
232 // http://bugs.php.net/bug.php?id=42465
233 mt_srand( getmypid() );
234 }
235
236 /**
237 * Resets the given service for testing purposes.
238 *
239 * @warning This is generally unsafe! Other services may still retain references
240 * to the stale service instance, leading to failures and inconsistencies. Subclasses
241 * may use this method to reset specific services under specific instances, but
242 * it should not be exposed to application logic.
243 *
244 * @note With proper dependency injection used throughout the codebase, this method
245 * should not be needed. It is provided to allow tests that pollute global service
246 * instances to clean up.
247 *
248 * @param string $name
249 * @param string $destroy Whether the service instance should be destroyed if it exists.
250 * When set to false, any existing service instance will effectively be detached
251 * from the container.
252 *
253 * @throws MWException if called outside of PHPUnit tests.
254 */
255 public function resetServiceForTesting( $name, $destroy = true ) {
256 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
257 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
258 }
259
260 $this->resetService( $name, $destroy );
261 }
262
263 /**
264 * Convenience method that throws an exception unless it is called during a phase in which
265 * resetting of global services is allowed. In general, services should not be reset
266 * individually, since that may introduce inconsistencies.
267 *
268 * This method will throw an exception if:
269 *
270 * - self::$resetInProgress is false (to allow all services to be reset together
271 * via resetGlobalInstance)
272 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
273 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
274 *
275 * This method is intended to be used to safeguard against accidentally resetting
276 * global service instances that are not yet managed by MediaWikiServices. It is
277 * defined here in the MediaWikiServices services class to have a central place
278 * for managing service bootstrapping and resetting.
279 *
280 * @param string $method the name of the caller method, as given by __METHOD__.
281 *
282 * @throws MWException if called outside bootstrap mode.
283 *
284 * @see resetGlobalInstance()
285 * @see forceGlobalInstance()
286 * @see disableStorageBackend()
287 */
288 public static function failIfResetNotAllowed( $method ) {
289 if ( !defined( 'MW_PHPUNIT_TEST' )
290 && !defined( 'MW_PARSER_TEST' )
291 && !defined( 'MEDIAWIKI_INSTALL' )
292 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
293 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
294 ) {
295 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
296 }
297 }
298
299 /**
300 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
301 * This has to contain at least the information needed to set up the 'ConfigFactory'
302 * service.
303 */
304 public function __construct( Config $config ) {
305 parent::__construct();
306
307 // Register the given Config object as the bootstrap config service.
308 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
309 return $config;
310 } );
311 }
312
313 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
314
315 /**
316 * Returns the Config object containing the bootstrap configuration.
317 * Bootstrap configuration would typically include database credentials
318 * and other information that may be needed before the ConfigFactory
319 * service can be instantiated.
320 *
321 * @note This should only be used during bootstrapping, in particular
322 * when creating the MainConfig service. Application logic should
323 * use getMainConfig() to get a Config instances.
324 *
325 * @return Config
326 */
327 public function getBootstrapConfig() {
328 return $this->getService( 'BootstrapConfig' );
329 }
330
331 /**
332 * @return ConfigFactory
333 */
334 public function getConfigFactory() {
335 return $this->getService( 'ConfigFactory' );
336 }
337
338 /**
339 * Returns the Config object that provides configuration for MediaWiki core.
340 * This may or may not be the same object that is returned by getBootstrapConfig().
341 *
342 * @return Config
343 */
344 public function getMainConfig() {
345 return $this->getService( 'MainConfig' );
346 }
347
348 /**
349 * @return SiteLookup
350 */
351 public function getSiteLookup() {
352 return $this->getService( 'SiteLookup' );
353 }
354
355 /**
356 * @return SiteStore
357 */
358 public function getSiteStore() {
359 return $this->getService( 'SiteStore' );
360 }
361
362 /**
363 * @return StatsdDataFactory
364 */
365 public function getStatsdDataFactory() {
366 return $this->getService( 'StatsdDataFactory' );
367 }
368
369 /**
370 * @return EventRelayerGroup
371 */
372 public function getEventRelayerGroup() {
373 return $this->getService( 'EventRelayerGroup' );
374 }
375
376 /**
377 * @return SearchEngine
378 */
379 public function newSearchEngine() {
380 // New engine object every time, since they keep state
381 return $this->getService( 'SearchEngineFactory' )->create();
382 }
383
384 /**
385 * @return SearchEngineFactory
386 */
387 public function getSearchEngineFactory() {
388 return $this->getService( 'SearchEngineFactory' );
389 }
390
391 /**
392 * @return SearchEngineConfig
393 */
394 public function getSearchEngineConfig() {
395 return $this->getService( 'SearchEngineConfig' );
396 }
397
398 /**
399 * @return SkinFactory
400 */
401 public function getSkinFactory() {
402 return $this->getService( 'SkinFactory' );
403 }
404
405 /**
406 * @return LBFactory
407 */
408 public function getDBLoadBalancerFactory() {
409 return $this->getService( 'DBLoadBalancerFactory' );
410 }
411
412 /**
413 * @return LoadBalancer The main DB load balancer for the local wiki.
414 */
415 public function getDBLoadBalancer() {
416 return $this->getService( 'DBLoadBalancer' );
417 }
418
419 /**
420 * @return WatchedItemStore
421 */
422 public function getWatchedItemStore() {
423 return $this->getService( 'WatchedItemStore' );
424 }
425
426 /**
427 * @since 1.28
428 * @return GenderCache
429 */
430 public function getGenderCache() {
431 return $this->getService( 'GenderCache' );
432 }
433
434 ///////////////////////////////////////////////////////////////////////////
435 // NOTE: When adding a service getter here, don't forget to add a test
436 // case for it in MediaWikiServicesTest::provideGetters() and in
437 // MediaWikiServicesTest::provideGetService()!
438 ///////////////////////////////////////////////////////////////////////////
439
440 }