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
;
24 use SearchEngineConfig
;
25 use SearchEngineFactory
;
29 use WatchedItemQueryService
;
33 use VirtualRESTServiceClient
;
34 use MediaWiki\Interwiki\InterwikiLookup
;
37 * Service locator for MediaWiki core services.
39 * This program is free software; you can redistribute it and/or modify
40 * it under the terms of the GNU General Public License as published by
41 * the Free Software Foundation; either version 2 of the License, or
42 * (at your option) any later version.
44 * This program is distributed in the hope that it will be useful,
45 * but WITHOUT ANY WARRANTY; without even the implied warranty of
46 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
47 * GNU General Public License for more details.
49 * You should have received a copy of the GNU General Public License along
50 * with this program; if not, write to the Free Software Foundation, Inc.,
51 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
52 * http://www.gnu.org/copyleft/gpl.html
60 * MediaWikiServices is the service locator for the application scope of MediaWiki.
61 * Its implemented as a simple configurable DI container.
62 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
63 * the network of service objects that defines MediaWiki's application logic.
64 * It acts as an entry point to MediaWiki's dependency injection mechanism.
66 * Services are defined in the "wiring" array passed to the constructor,
67 * or by calling defineService().
69 * @see docs/injection.txt for an overview of using dependency injection in the
70 * MediaWiki code base.
72 class MediaWikiServices
extends ServiceContainer
{
75 * @var MediaWikiServices|null
77 private static $instance = null;
80 * Returns the global default instance of the top level service locator.
84 * The default instance is initialized using the service instantiator functions
85 * defined in ServiceWiring.php.
87 * @note This should only be called by static functions! The instance returned here
88 * should not be passed around! Objects that need access to a service should have
89 * that service injected into the constructor, never a service locator!
91 * @return MediaWikiServices
93 public static function getInstance() {
94 if ( self
::$instance === null ) {
95 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
96 // but some information from the global scope has to be injected here,
97 // even if it's just a file name or database credentials to load
98 // configuration from.
99 $bootstrapConfig = new GlobalVarConfig();
100 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
103 return self
::$instance;
107 * Replaces the global MediaWikiServices instance.
111 * @note This is for use in PHPUnit tests only!
113 * @throws MWException if called outside of PHPUnit tests.
115 * @param MediaWikiServices $services The new MediaWikiServices object.
117 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
119 public static function forceGlobalInstance( MediaWikiServices
$services ) {
120 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
121 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
124 $old = self
::getInstance();
125 self
::$instance = $services;
131 * Creates a new instance of MediaWikiServices and sets it as the global default
132 * instance. getInstance() will return a different MediaWikiServices object
133 * after every call to resetGlobalInstance().
137 * @warning This should not be used during normal operation. It is intended for use
138 * when the configuration has changed significantly since bootstrap time, e.g.
139 * during the installation process or during testing.
141 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
142 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
143 * any of the services managed by MediaWikiServices exist. If any service objects
144 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
145 * with the operation of the services managed by the new MediaWikiServices.
146 * Operating with a mix of services created by the old and the new
147 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
148 * Any class implementing LAZY LOADING is especially prone to this problem,
149 * since instances would typically retain a reference to a storage layer service.
151 * @see forceGlobalInstance()
152 * @see resetGlobalInstance()
153 * @see resetBetweenTest()
155 * @param Config|null $bootstrapConfig The Config object to be registered as the
156 * 'BootstrapConfig' service. This has to contain at least the information
157 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
158 * config of the old instance of MediaWikiServices will be re-used. If there
159 * was no previous instance, a new GlobalVarConfig object will be used to
160 * bootstrap the services.
162 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
163 * See SalvageableService for details.
165 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
166 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
169 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
170 if ( self
::$instance === null ) {
171 // no global instance yet, nothing to reset
175 self
::failIfResetNotAllowed( __METHOD__
);
177 if ( $bootstrapConfig === null ) {
178 $bootstrapConfig = self
::$instance->getBootstrapConfig();
181 $oldInstance = self
::$instance;
183 self
::$instance = self
::newInstance( $bootstrapConfig );
184 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
186 if ( $quick === 'quick' ) {
187 self
::$instance->salvage( $oldInstance );
189 $oldInstance->destroy();
195 * Salvages the state of any salvageable service instances in $other.
197 * @note $other will have been destroyed when salvage() returns.
199 * @param MediaWikiServices $other
201 private function salvage( self
$other ) {
202 foreach ( $this->getServiceNames() as $name ) {
203 // The service could be new in the new instance and not registered in the
204 // other instance (e.g. an extension that was loaded after the instantiation of
205 // the other instance. Skip this service in this case. See T143974
207 $oldService = $other->peekService( $name );
208 } catch ( NoSuchServiceException
$e ) {
212 if ( $oldService instanceof SalvageableService
) {
213 /** @var SalvageableService $newService */
214 $newService = $this->getService( $name );
215 $newService->salvage( $oldService );
223 * Creates a new MediaWikiServices instance and initializes it according to the
224 * given $bootstrapConfig. In particular, all wiring files defined in the
225 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
227 * @param Config|null $bootstrapConfig The Config object to be registered as the
228 * 'BootstrapConfig' service.
230 * @param string $loadWiring set this to 'load' to load the wiring files specified
231 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
233 * @return MediaWikiServices
234 * @throws MWException
235 * @throws \FatalError
237 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
238 $instance = new self( $bootstrapConfig );
240 // Load the default wiring from the specified files.
241 if ( $loadWiring === 'load' ) {
242 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
243 $instance->loadWiringFiles( $wiringFiles );
246 // Provide a traditional hook point to allow extensions to configure services.
247 Hooks
::run( 'MediaWikiServices', [ $instance ] );
253 * Disables all storage layer services. After calling this, any attempt to access the
254 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
259 * @warning This is intended for extreme situations only and should never be used
260 * while serving normal web requests. Legitimate use cases for this method include
261 * the installation process. Test fixtures may also use this, if the fixture relies
264 * @see resetGlobalInstance()
265 * @see resetChildProcessServices()
267 public static function disableStorageBackend() {
268 // TODO: also disable some Caches, JobQueues, etc
269 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
270 $services = self
::getInstance();
272 foreach ( $destroy as $name ) {
273 $services->disableService( $name );
276 ObjectCache
::clear();
280 * Resets any services that may have become stale after a child process
281 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
282 * to call this method from the parent process.
286 * @note This is intended for use in the context of process forking only!
288 * @see resetGlobalInstance()
289 * @see disableStorageBackend()
291 public static function resetChildProcessServices() {
292 // NOTE: for now, just reset everything. Since we don't know the interdependencies
293 // between services, we can't do this more selectively at this time.
294 self
::resetGlobalInstance();
296 // Child, reseed because there is no bug in PHP:
297 // http://bugs.php.net/bug.php?id=42465
298 mt_srand( getmypid() );
302 * Resets the given service for testing purposes.
306 * @warning This is generally unsafe! Other services may still retain references
307 * to the stale service instance, leading to failures and inconsistencies. Subclasses
308 * may use this method to reset specific services under specific instances, but
309 * it should not be exposed to application logic.
311 * @note With proper dependency injection used throughout the codebase, this method
312 * should not be needed. It is provided to allow tests that pollute global service
313 * instances to clean up.
315 * @param string $name
316 * @param bool $destroy Whether the service instance should be destroyed if it exists.
317 * When set to false, any existing service instance will effectively be detached
318 * from the container.
320 * @throws MWException if called outside of PHPUnit tests.
322 public function resetServiceForTesting( $name, $destroy = true ) {
323 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
324 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
327 $this->resetService( $name, $destroy );
331 * Convenience method that throws an exception unless it is called during a phase in which
332 * resetting of global services is allowed. In general, services should not be reset
333 * individually, since that may introduce inconsistencies.
337 * This method will throw an exception if:
339 * - self::$resetInProgress is false (to allow all services to be reset together
340 * via resetGlobalInstance)
341 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
342 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
344 * This method is intended to be used to safeguard against accidentally resetting
345 * global service instances that are not yet managed by MediaWikiServices. It is
346 * defined here in the MediaWikiServices services class to have a central place
347 * for managing service bootstrapping and resetting.
349 * @param string $method the name of the caller method, as given by __METHOD__.
351 * @throws MWException if called outside bootstrap mode.
353 * @see resetGlobalInstance()
354 * @see forceGlobalInstance()
355 * @see disableStorageBackend()
357 public static function failIfResetNotAllowed( $method ) {
358 if ( !defined( 'MW_PHPUNIT_TEST' )
359 && !defined( 'MW_PARSER_TEST' )
360 && !defined( 'MEDIAWIKI_INSTALL' )
361 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
362 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
364 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
369 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
370 * This has to contain at least the information needed to set up the 'ConfigFactory'
373 public function __construct( Config
$config ) {
374 parent
::__construct();
376 // Register the given Config object as the bootstrap config service.
377 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
382 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
385 * Returns the Config object containing the bootstrap configuration.
386 * Bootstrap configuration would typically include database credentials
387 * and other information that may be needed before the ConfigFactory
388 * service can be instantiated.
390 * @note This should only be used during bootstrapping, in particular
391 * when creating the MainConfig service. Application logic should
392 * use getMainConfig() to get a Config instances.
397 public function getBootstrapConfig() {
398 return $this->getService( 'BootstrapConfig' );
403 * @return ConfigFactory
405 public function getConfigFactory() {
406 return $this->getService( 'ConfigFactory' );
410 * Returns the Config object that provides configuration for MediaWiki core.
411 * This may or may not be the same object that is returned by getBootstrapConfig().
416 public function getMainConfig() {
417 return $this->getService( 'MainConfig' );
424 public function getSiteLookup() {
425 return $this->getService( 'SiteLookup' );
432 public function getSiteStore() {
433 return $this->getService( 'SiteStore' );
438 * @return InterwikiLookup
440 public function getInterwikiLookup() {
441 return $this->getService( 'InterwikiLookup' );
446 * @return StatsdDataFactory
448 public function getStatsdDataFactory() {
449 return $this->getService( 'StatsdDataFactory' );
454 * @return EventRelayerGroup
456 public function getEventRelayerGroup() {
457 return $this->getService( 'EventRelayerGroup' );
462 * @return SearchEngine
464 public function newSearchEngine() {
465 // New engine object every time, since they keep state
466 return $this->getService( 'SearchEngineFactory' )->create();
471 * @return SearchEngineFactory
473 public function getSearchEngineFactory() {
474 return $this->getService( 'SearchEngineFactory' );
479 * @return SearchEngineConfig
481 public function getSearchEngineConfig() {
482 return $this->getService( 'SearchEngineConfig' );
487 * @return SkinFactory
489 public function getSkinFactory() {
490 return $this->getService( 'SkinFactory' );
497 public function getDBLoadBalancerFactory() {
498 return $this->getService( 'DBLoadBalancerFactory' );
503 * @return LoadBalancer The main DB load balancer for the local wiki.
505 public function getDBLoadBalancer() {
506 return $this->getService( 'DBLoadBalancer' );
511 * @return WatchedItemStore
513 public function getWatchedItemStore() {
514 return $this->getService( 'WatchedItemStore' );
519 * @return WatchedItemQueryService
521 public function getWatchedItemQueryService() {
522 return $this->getService( 'WatchedItemQueryService' );
527 * @return MediaHandlerFactory
529 public function getMediaHandlerFactory() {
530 return $this->getService( 'MediaHandlerFactory' );
535 * @return ProxyLookup
537 public function getProxyLookup() {
538 return $this->getService( 'ProxyLookup' );
543 * @return GenderCache
545 public function getGenderCache() {
546 return $this->getService( 'GenderCache' );
553 public function getLinkCache() {
554 return $this->getService( 'LinkCache' );
559 * @return LinkRendererFactory
561 public function getLinkRendererFactory() {
562 return $this->getService( 'LinkRendererFactory' );
566 * LinkRenderer instance that can be used
567 * if no custom options are needed
570 * @return LinkRenderer
572 public function getLinkRenderer() {
573 return $this->getService( 'LinkRenderer' );
578 * @return TitleFormatter
580 public function getTitleFormatter() {
581 return $this->getService( 'TitleFormatter' );
586 * @return TitleParser
588 public function getTitleParser() {
589 return $this->getService( 'TitleParser' );
594 * @return VirtualRESTServiceClient
596 public function getVirtualRESTServiceClient() {
597 return $this->getService( 'VirtualRESTServiceClient' );
600 ///////////////////////////////////////////////////////////////////////////
601 // NOTE: When adding a service getter here, don't forget to add a test
602 // case for it in MediaWikiServicesTest::provideGetters() and in
603 // MediaWikiServicesTest::provideGetService()!
604 ///////////////////////////////////////////////////////////////////////////