12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
14 use MediaHandlerFactory
;
15 use MediaWiki\Linker\LinkRenderer
;
16 use MediaWiki\Linker\LinkRendererFactory
;
17 use MediaWiki\Services\SalvageableService
;
18 use MediaWiki\Services\ServiceContainer
;
19 use MediaWiki\Services\NoSuchServiceException
;
23 use SearchEngineConfig
;
24 use SearchEngineFactory
;
28 use WatchedItemQueryService
;
32 use VirtualRESTServiceClient
;
33 use MediaWiki\Interwiki\InterwikiLookup
;
36 * Service locator for MediaWiki core services.
38 * This program is free software; you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation; either version 2 of the License, or
41 * (at your option) any later version.
43 * This program is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 * GNU General Public License for more details.
48 * You should have received a copy of the GNU General Public License along
49 * with this program; if not, write to the Free Software Foundation, Inc.,
50 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
51 * http://www.gnu.org/copyleft/gpl.html
59 * MediaWikiServices is the service locator for the application scope of MediaWiki.
60 * Its implemented as a simple configurable DI container.
61 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
62 * the network of service objects that defines MediaWiki's application logic.
63 * It acts as an entry point to MediaWiki's dependency injection mechanism.
65 * Services are defined in the "wiring" array passed to the constructor,
66 * or by calling defineService().
68 * @see docs/injection.txt for an overview of using dependency injection in the
69 * MediaWiki code base.
71 class MediaWikiServices
extends ServiceContainer
{
74 * @var MediaWikiServices|null
76 private static $instance = null;
79 * Returns the global default instance of the top level service locator.
83 * The default instance is initialized using the service instantiator functions
84 * defined in ServiceWiring.php.
86 * @note This should only be called by static functions! The instance returned here
87 * should not be passed around! Objects that need access to a service should have
88 * that service injected into the constructor, never a service locator!
90 * @return MediaWikiServices
92 public static function getInstance() {
93 if ( self
::$instance === null ) {
94 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
95 // but some information from the global scope has to be injected here,
96 // even if it's just a file name or database credentials to load
97 // configuration from.
98 $bootstrapConfig = new GlobalVarConfig();
99 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
102 return self
::$instance;
106 * Replaces the global MediaWikiServices instance.
110 * @note This is for use in PHPUnit tests only!
112 * @throws MWException if called outside of PHPUnit tests.
114 * @param MediaWikiServices $services The new MediaWikiServices object.
116 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
118 public static function forceGlobalInstance( MediaWikiServices
$services ) {
119 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
120 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
123 $old = self
::getInstance();
124 self
::$instance = $services;
130 * Creates a new instance of MediaWikiServices and sets it as the global default
131 * instance. getInstance() will return a different MediaWikiServices object
132 * after every call to resetGlobalInstance().
136 * @warning This should not be used during normal operation. It is intended for use
137 * when the configuration has changed significantly since bootstrap time, e.g.
138 * during the installation process or during testing.
140 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
141 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
142 * any of the services managed by MediaWikiServices exist. If any service objects
143 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
144 * with the operation of the services managed by the new MediaWikiServices.
145 * Operating with a mix of services created by the old and the new
146 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
147 * Any class implementing LAZY LOADING is especially prone to this problem,
148 * since instances would typically retain a reference to a storage layer service.
150 * @see forceGlobalInstance()
151 * @see resetGlobalInstance()
152 * @see resetBetweenTest()
154 * @param Config|null $bootstrapConfig The Config object to be registered as the
155 * 'BootstrapConfig' service. This has to contain at least the information
156 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
157 * config of the old instance of MediaWikiServices will be re-used. If there
158 * was no previous instance, a new GlobalVarConfig object will be used to
159 * bootstrap the services.
161 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
162 * See SalvageableService for details.
164 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
165 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
168 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
169 if ( self
::$instance === null ) {
170 // no global instance yet, nothing to reset
174 self
::failIfResetNotAllowed( __METHOD__
);
176 if ( $bootstrapConfig === null ) {
177 $bootstrapConfig = self
::$instance->getBootstrapConfig();
180 $oldInstance = self
::$instance;
182 self
::$instance = self
::newInstance( $bootstrapConfig );
183 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
185 if ( $quick === 'quick' ) {
186 self
::$instance->salvage( $oldInstance );
188 $oldInstance->destroy();
194 * Salvages the state of any salvageable service instances in $other.
196 * @note $other will have been destroyed when salvage() returns.
198 * @param MediaWikiServices $other
200 private function salvage( self
$other ) {
201 foreach ( $this->getServiceNames() as $name ) {
202 // The service could be new in the new instance and not registered in the
203 // other instance (e.g. an extension that was loaded after the instantiation of
204 // the other instance. Skip this service in this case. See T143974
206 $oldService = $other->peekService( $name );
207 } catch ( NoSuchServiceException
$e ) {
211 if ( $oldService instanceof SalvageableService
) {
212 /** @var SalvageableService $newService */
213 $newService = $this->getService( $name );
214 $newService->salvage( $oldService );
222 * Creates a new MediaWikiServices instance and initializes it according to the
223 * given $bootstrapConfig. In particular, all wiring files defined in the
224 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
226 * @param Config|null $bootstrapConfig The Config object to be registered as the
227 * 'BootstrapConfig' service.
229 * @param string $loadWiring set this to 'load' to load the wiring files specified
230 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
232 * @return MediaWikiServices
233 * @throws MWException
234 * @throws \FatalError
236 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
237 $instance = new self( $bootstrapConfig );
239 // Load the default wiring from the specified files.
240 if ( $loadWiring === 'load' ) {
241 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
242 $instance->loadWiringFiles( $wiringFiles );
245 // Provide a traditional hook point to allow extensions to configure services.
246 Hooks
::run( 'MediaWikiServices', [ $instance ] );
252 * Disables all storage layer services. After calling this, any attempt to access the
253 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
258 * @warning This is intended for extreme situations only and should never be used
259 * while serving normal web requests. Legitimate use cases for this method include
260 * the installation process. Test fixtures may also use this, if the fixture relies
263 * @see resetGlobalInstance()
264 * @see resetChildProcessServices()
266 public static function disableStorageBackend() {
267 // TODO: also disable some Caches, JobQueues, etc
268 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
269 $services = self
::getInstance();
271 foreach ( $destroy as $name ) {
272 $services->disableService( $name );
275 ObjectCache
::clear();
279 * Resets any services that may have become stale after a child process
280 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
281 * to call this method from the parent process.
285 * @note This is intended for use in the context of process forking only!
287 * @see resetGlobalInstance()
288 * @see disableStorageBackend()
290 public static function resetChildProcessServices() {
291 // NOTE: for now, just reset everything. Since we don't know the interdependencies
292 // between services, we can't do this more selectively at this time.
293 self
::resetGlobalInstance();
295 // Child, reseed because there is no bug in PHP:
296 // http://bugs.php.net/bug.php?id=42465
297 mt_srand( getmypid() );
301 * Resets the given service for testing purposes.
305 * @warning This is generally unsafe! Other services may still retain references
306 * to the stale service instance, leading to failures and inconsistencies. Subclasses
307 * may use this method to reset specific services under specific instances, but
308 * it should not be exposed to application logic.
310 * @note With proper dependency injection used throughout the codebase, this method
311 * should not be needed. It is provided to allow tests that pollute global service
312 * instances to clean up.
314 * @param string $name
315 * @param bool $destroy Whether the service instance should be destroyed if it exists.
316 * When set to false, any existing service instance will effectively be detached
317 * from the container.
319 * @throws MWException if called outside of PHPUnit tests.
321 public function resetServiceForTesting( $name, $destroy = true ) {
322 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
323 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
326 $this->resetService( $name, $destroy );
330 * Convenience method that throws an exception unless it is called during a phase in which
331 * resetting of global services is allowed. In general, services should not be reset
332 * individually, since that may introduce inconsistencies.
336 * This method will throw an exception if:
338 * - self::$resetInProgress is false (to allow all services to be reset together
339 * via resetGlobalInstance)
340 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
341 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
343 * This method is intended to be used to safeguard against accidentally resetting
344 * global service instances that are not yet managed by MediaWikiServices. It is
345 * defined here in the MediaWikiServices services class to have a central place
346 * for managing service bootstrapping and resetting.
348 * @param string $method the name of the caller method, as given by __METHOD__.
350 * @throws MWException if called outside bootstrap mode.
352 * @see resetGlobalInstance()
353 * @see forceGlobalInstance()
354 * @see disableStorageBackend()
356 public static function failIfResetNotAllowed( $method ) {
357 if ( !defined( 'MW_PHPUNIT_TEST' )
358 && !defined( 'MW_PARSER_TEST' )
359 && !defined( 'MEDIAWIKI_INSTALL' )
360 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
361 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
363 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
368 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
369 * This has to contain at least the information needed to set up the 'ConfigFactory'
372 public function __construct( Config
$config ) {
373 parent
::__construct();
375 // Register the given Config object as the bootstrap config service.
376 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
381 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
384 * Returns the Config object containing the bootstrap configuration.
385 * Bootstrap configuration would typically include database credentials
386 * and other information that may be needed before the ConfigFactory
387 * service can be instantiated.
389 * @note This should only be used during bootstrapping, in particular
390 * when creating the MainConfig service. Application logic should
391 * use getMainConfig() to get a Config instances.
396 public function getBootstrapConfig() {
397 return $this->getService( 'BootstrapConfig' );
402 * @return ConfigFactory
404 public function getConfigFactory() {
405 return $this->getService( 'ConfigFactory' );
409 * Returns the Config object that provides configuration for MediaWiki core.
410 * This may or may not be the same object that is returned by getBootstrapConfig().
415 public function getMainConfig() {
416 return $this->getService( 'MainConfig' );
423 public function getSiteLookup() {
424 return $this->getService( 'SiteLookup' );
431 public function getSiteStore() {
432 return $this->getService( 'SiteStore' );
437 * @return InterwikiLookup
439 public function getInterwikiLookup() {
440 return $this->getService( 'InterwikiLookup' );
445 * @return StatsdDataFactory
447 public function getStatsdDataFactory() {
448 return $this->getService( 'StatsdDataFactory' );
453 * @return EventRelayerGroup
455 public function getEventRelayerGroup() {
456 return $this->getService( 'EventRelayerGroup' );
461 * @return SearchEngine
463 public function newSearchEngine() {
464 // New engine object every time, since they keep state
465 return $this->getService( 'SearchEngineFactory' )->create();
470 * @return SearchEngineFactory
472 public function getSearchEngineFactory() {
473 return $this->getService( 'SearchEngineFactory' );
478 * @return SearchEngineConfig
480 public function getSearchEngineConfig() {
481 return $this->getService( 'SearchEngineConfig' );
486 * @return SkinFactory
488 public function getSkinFactory() {
489 return $this->getService( 'SkinFactory' );
496 public function getDBLoadBalancerFactory() {
497 return $this->getService( 'DBLoadBalancerFactory' );
502 * @return LoadBalancer The main DB load balancer for the local wiki.
504 public function getDBLoadBalancer() {
505 return $this->getService( 'DBLoadBalancer' );
510 * @return WatchedItemStore
512 public function getWatchedItemStore() {
513 return $this->getService( 'WatchedItemStore' );
518 * @return WatchedItemQueryService
520 public function getWatchedItemQueryService() {
521 return $this->getService( 'WatchedItemQueryService' );
526 * @return MediaHandlerFactory
528 public function getMediaHandlerFactory() {
529 return $this->getService( 'MediaHandlerFactory' );
534 * @return GenderCache
536 public function getGenderCache() {
537 return $this->getService( 'GenderCache' );
544 public function getLinkCache() {
545 return $this->getService( 'LinkCache' );
550 * @return LinkRendererFactory
552 public function getLinkRendererFactory() {
553 return $this->getService( 'LinkRendererFactory' );
557 * LinkRenderer instance that can be used
558 * if no custom options are needed
561 * @return LinkRenderer
563 public function getLinkRenderer() {
564 return $this->getService( 'LinkRenderer' );
569 * @return TitleFormatter
571 public function getTitleFormatter() {
572 return $this->getService( 'TitleFormatter' );
577 * @return TitleParser
579 public function getTitleParser() {
580 return $this->getService( 'TitleParser' );
585 * @return VirtualRESTServiceClient
587 public function getVirtualRESTServiceClient() {
588 return $this->getService( 'VirtualRESTServiceClient' );
591 ///////////////////////////////////////////////////////////////////////////
592 // NOTE: When adding a service getter here, don't forget to add a test
593 // case for it in MediaWikiServicesTest::provideGetters() and in
594 // MediaWikiServicesTest::provideGetService()!
595 ///////////////////////////////////////////////////////////////////////////