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
;
22 use SearchEngineConfig
;
23 use SearchEngineFactory
;
27 use WatchedItemQueryService
;
31 use VirtualRESTServiceClient
;
32 use MediaWiki\Interwiki\InterwikiLookup
;
35 * Service locator for MediaWiki core services.
37 * This program is free software; you can redistribute it and/or modify
38 * it under the terms of the GNU General Public License as published by
39 * the Free Software Foundation; either version 2 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
47 * You should have received a copy of the GNU General Public License along
48 * with this program; if not, write to the Free Software Foundation, Inc.,
49 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
50 * http://www.gnu.org/copyleft/gpl.html
58 * MediaWikiServices is the service locator for the application scope of MediaWiki.
59 * Its implemented as a simple configurable DI container.
60 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
61 * the network of service objects that defines MediaWiki's application logic.
62 * It acts as an entry point to MediaWiki's dependency injection mechanism.
64 * Services are defined in the "wiring" array passed to the constructor,
65 * or by calling defineService().
67 * @see docs/injection.txt for an overview of using dependency injection in the
68 * MediaWiki code base.
70 class MediaWikiServices
extends ServiceContainer
{
73 * @var MediaWikiServices|null
75 private static $instance = null;
78 * Returns the global default instance of the top level service locator.
82 * The default instance is initialized using the service instantiator functions
83 * defined in ServiceWiring.php.
85 * @note This should only be called by static functions! The instance returned here
86 * should not be passed around! Objects that need access to a service should have
87 * that service injected into the constructor, never a service locator!
89 * @return MediaWikiServices
91 public static function getInstance() {
92 if ( self
::$instance === null ) {
93 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
94 // but some information from the global scope has to be injected here,
95 // even if it's just a file name or database credentials to load
96 // configuration from.
97 $bootstrapConfig = new GlobalVarConfig();
98 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
101 return self
::$instance;
105 * Replaces the global MediaWikiServices instance.
109 * @note This is for use in PHPUnit tests only!
111 * @throws MWException if called outside of PHPUnit tests.
113 * @param MediaWikiServices $services The new MediaWikiServices object.
115 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
117 public static function forceGlobalInstance( MediaWikiServices
$services ) {
118 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
119 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
122 $old = self
::getInstance();
123 self
::$instance = $services;
129 * Creates a new instance of MediaWikiServices and sets it as the global default
130 * instance. getInstance() will return a different MediaWikiServices object
131 * after every call to resetGlobalInstance().
135 * @warning This should not be used during normal operation. It is intended for use
136 * when the configuration has changed significantly since bootstrap time, e.g.
137 * during the installation process or during testing.
139 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
140 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
141 * any of the services managed by MediaWikiServices exist. If any service objects
142 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
143 * with the operation of the services managed by the new MediaWikiServices.
144 * Operating with a mix of services created by the old and the new
145 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
146 * Any class implementing LAZY LOADING is especially prone to this problem,
147 * since instances would typically retain a reference to a storage layer service.
149 * @see forceGlobalInstance()
150 * @see resetGlobalInstance()
151 * @see resetBetweenTest()
153 * @param Config|null $bootstrapConfig The Config object to be registered as the
154 * 'BootstrapConfig' service. This has to contain at least the information
155 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
156 * config of the old instance of MediaWikiServices will be re-used. If there
157 * was no previous instance, a new GlobalVarConfig object will be used to
158 * bootstrap the services.
160 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
161 * See SalvageableService for details.
163 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
164 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
167 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
168 if ( self
::$instance === null ) {
169 // no global instance yet, nothing to reset
173 self
::failIfResetNotAllowed( __METHOD__
);
175 if ( $bootstrapConfig === null ) {
176 $bootstrapConfig = self
::$instance->getBootstrapConfig();
179 $oldInstance = self
::$instance;
181 self
::$instance = self
::newInstance( $bootstrapConfig );
182 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
184 if ( $quick === 'quick' ) {
185 self
::$instance->salvage( $oldInstance );
187 $oldInstance->destroy();
193 * Salvages the state of any salvageable service instances in $other.
195 * @note $other will have been destroyed when salvage() returns.
197 * @param MediaWikiServices $other
199 private function salvage( self
$other ) {
200 foreach ( $this->getServiceNames() as $name ) {
201 // The service could be new in the new instance and not registered in the
202 // other instance (e.g. an extension that was loaded after the instantiation of
203 // the other instance. Skip this service in this case. See T143974
205 $oldService = $other->peekService( $name );
206 } catch ( NoSuchServiceException
$e ) {
210 if ( $oldService instanceof SalvageableService
) {
211 /** @var SalvageableService $newService */
212 $newService = $this->getService( $name );
213 $newService->salvage( $oldService );
221 * Creates a new MediaWikiServices instance and initializes it according to the
222 * given $bootstrapConfig. In particular, all wiring files defined in the
223 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
225 * @param Config|null $bootstrapConfig The Config object to be registered as the
226 * 'BootstrapConfig' service.
228 * @param string $loadWiring set this to 'load' to load the wiring files specified
229 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
231 * @return MediaWikiServices
232 * @throws MWException
233 * @throws \FatalError
235 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
236 $instance = new self( $bootstrapConfig );
238 // Load the default wiring from the specified files.
239 if ( $loadWiring === 'load' ) {
240 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
241 $instance->loadWiringFiles( $wiringFiles );
244 // Provide a traditional hook point to allow extensions to configure services.
245 Hooks
::run( 'MediaWikiServices', [ $instance ] );
251 * Disables all storage layer services. After calling this, any attempt to access the
252 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
257 * @warning This is intended for extreme situations only and should never be used
258 * while serving normal web requests. Legitimate use cases for this method include
259 * the installation process. Test fixtures may also use this, if the fixture relies
262 * @see resetGlobalInstance()
263 * @see resetChildProcessServices()
265 public static function disableStorageBackend() {
266 // TODO: also disable some Caches, JobQueues, etc
267 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
268 $services = self
::getInstance();
270 foreach ( $destroy as $name ) {
271 $services->disableService( $name );
274 ObjectCache
::clear();
278 * Resets any services that may have become stale after a child process
279 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
280 * to call this method from the parent process.
284 * @note This is intended for use in the context of process forking only!
286 * @see resetGlobalInstance()
287 * @see disableStorageBackend()
289 public static function resetChildProcessServices() {
290 // NOTE: for now, just reset everything. Since we don't know the interdependencies
291 // between services, we can't do this more selectively at this time.
292 self
::resetGlobalInstance();
294 // Child, reseed because there is no bug in PHP:
295 // http://bugs.php.net/bug.php?id=42465
296 mt_srand( getmypid() );
300 * Resets the given service for testing purposes.
304 * @warning This is generally unsafe! Other services may still retain references
305 * to the stale service instance, leading to failures and inconsistencies. Subclasses
306 * may use this method to reset specific services under specific instances, but
307 * it should not be exposed to application logic.
309 * @note With proper dependency injection used throughout the codebase, this method
310 * should not be needed. It is provided to allow tests that pollute global service
311 * instances to clean up.
313 * @param string $name
314 * @param bool $destroy Whether the service instance should be destroyed if it exists.
315 * When set to false, any existing service instance will effectively be detached
316 * from the container.
318 * @throws MWException if called outside of PHPUnit tests.
320 public function resetServiceForTesting( $name, $destroy = true ) {
321 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
322 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
325 $this->resetService( $name, $destroy );
329 * Convenience method that throws an exception unless it is called during a phase in which
330 * resetting of global services is allowed. In general, services should not be reset
331 * individually, since that may introduce inconsistencies.
335 * This method will throw an exception if:
337 * - self::$resetInProgress is false (to allow all services to be reset together
338 * via resetGlobalInstance)
339 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
340 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
342 * This method is intended to be used to safeguard against accidentally resetting
343 * global service instances that are not yet managed by MediaWikiServices. It is
344 * defined here in the MediaWikiServices services class to have a central place
345 * for managing service bootstrapping and resetting.
347 * @param string $method the name of the caller method, as given by __METHOD__.
349 * @throws MWException if called outside bootstrap mode.
351 * @see resetGlobalInstance()
352 * @see forceGlobalInstance()
353 * @see disableStorageBackend()
355 public static function failIfResetNotAllowed( $method ) {
356 if ( !defined( 'MW_PHPUNIT_TEST' )
357 && !defined( 'MW_PARSER_TEST' )
358 && !defined( 'MEDIAWIKI_INSTALL' )
359 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
360 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
362 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
367 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
368 * This has to contain at least the information needed to set up the 'ConfigFactory'
371 public function __construct( Config
$config ) {
372 parent
::__construct();
374 // Register the given Config object as the bootstrap config service.
375 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
380 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
383 * Returns the Config object containing the bootstrap configuration.
384 * Bootstrap configuration would typically include database credentials
385 * and other information that may be needed before the ConfigFactory
386 * service can be instantiated.
388 * @note This should only be used during bootstrapping, in particular
389 * when creating the MainConfig service. Application logic should
390 * use getMainConfig() to get a Config instances.
395 public function getBootstrapConfig() {
396 return $this->getService( 'BootstrapConfig' );
401 * @return ConfigFactory
403 public function getConfigFactory() {
404 return $this->getService( 'ConfigFactory' );
408 * Returns the Config object that provides configuration for MediaWiki core.
409 * This may or may not be the same object that is returned by getBootstrapConfig().
414 public function getMainConfig() {
415 return $this->getService( 'MainConfig' );
422 public function getSiteLookup() {
423 return $this->getService( 'SiteLookup' );
430 public function getSiteStore() {
431 return $this->getService( 'SiteStore' );
436 * @return InterwikiLookup
438 public function getInterwikiLookup() {
439 return $this->getService( 'InterwikiLookup' );
444 * @return StatsdDataFactory
446 public function getStatsdDataFactory() {
447 return $this->getService( 'StatsdDataFactory' );
452 * @return EventRelayerGroup
454 public function getEventRelayerGroup() {
455 return $this->getService( 'EventRelayerGroup' );
460 * @return SearchEngine
462 public function newSearchEngine() {
463 // New engine object every time, since they keep state
464 return $this->getService( 'SearchEngineFactory' )->create();
469 * @return SearchEngineFactory
471 public function getSearchEngineFactory() {
472 return $this->getService( 'SearchEngineFactory' );
477 * @return SearchEngineConfig
479 public function getSearchEngineConfig() {
480 return $this->getService( 'SearchEngineConfig' );
485 * @return SkinFactory
487 public function getSkinFactory() {
488 return $this->getService( 'SkinFactory' );
495 public function getDBLoadBalancerFactory() {
496 return $this->getService( 'DBLoadBalancerFactory' );
501 * @return LoadBalancer The main DB load balancer for the local wiki.
503 public function getDBLoadBalancer() {
504 return $this->getService( 'DBLoadBalancer' );
509 * @return WatchedItemStore
511 public function getWatchedItemStore() {
512 return $this->getService( 'WatchedItemStore' );
517 * @return WatchedItemQueryService
519 public function getWatchedItemQueryService() {
520 return $this->getService( 'WatchedItemQueryService' );
525 * @return MediaHandlerFactory
527 public function getMediaHandlerFactory() {
528 return $this->getService( 'MediaHandlerFactory' );
533 * @return GenderCache
535 public function getGenderCache() {
536 return $this->getService( 'GenderCache' );
543 public function getLinkCache() {
544 return $this->getService( 'LinkCache' );
549 * @return LinkRendererFactory
551 public function getLinkRendererFactory() {
552 return $this->getService( 'LinkRendererFactory' );
556 * LinkRenderer instance that can be used
557 * if no custom options are needed
560 * @return LinkRenderer
562 public function getLinkRenderer() {
563 return $this->getService( 'LinkRenderer' );
568 * @return TitleFormatter
570 public function getTitleFormatter() {
571 return $this->getService( 'TitleFormatter' );
576 * @return TitleParser
578 public function getTitleParser() {
579 return $this->getService( 'TitleParser' );
584 * @return VirtualRESTServiceClient
586 public function getVirtualRESTServiceClient() {
587 return $this->getService( 'VirtualRESTServiceClient' );
590 ///////////////////////////////////////////////////////////////////////////
591 // NOTE: When adding a service getter here, don't forget to add a test
592 // case for it in MediaWikiServicesTest::provideGetters() and in
593 // MediaWikiServicesTest::provideGetService()!
594 ///////////////////////////////////////////////////////////////////////////