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 MediaWiki\Interwiki\InterwikiLookup
;
34 * Service locator for MediaWiki core services.
36 * This program is free software; you can redistribute it and/or modify
37 * it under the terms of the GNU General Public License as published by
38 * the Free Software Foundation; either version 2 of the License, or
39 * (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License along
47 * with this program; if not, write to the Free Software Foundation, Inc.,
48 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
49 * http://www.gnu.org/copyleft/gpl.html
57 * MediaWikiServices is the service locator for the application scope of MediaWiki.
58 * Its implemented as a simple configurable DI container.
59 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
60 * the network of service objects that defines MediaWiki's application logic.
61 * It acts as an entry point to MediaWiki's dependency injection mechanism.
63 * Services are defined in the "wiring" array passed to the constructor,
64 * or by calling defineService().
66 * @see docs/injection.txt for an overview of using dependency injection in the
67 * MediaWiki code base.
69 class MediaWikiServices
extends ServiceContainer
{
72 * @var MediaWikiServices|null
74 private static $instance = null;
77 * Returns the global default instance of the top level service locator.
81 * The default instance is initialized using the service instantiator functions
82 * defined in ServiceWiring.php.
84 * @note This should only be called by static functions! The instance returned here
85 * should not be passed around! Objects that need access to a service should have
86 * that service injected into the constructor, never a service locator!
88 * @return MediaWikiServices
90 public static function getInstance() {
91 if ( self
::$instance === null ) {
92 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
93 // but some information from the global scope has to be injected here,
94 // even if it's just a file name or database credentials to load
95 // configuration from.
96 $bootstrapConfig = new GlobalVarConfig();
97 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
100 return self
::$instance;
104 * Replaces the global MediaWikiServices instance.
108 * @note This is for use in PHPUnit tests only!
110 * @throws MWException if called outside of PHPUnit tests.
112 * @param MediaWikiServices $services The new MediaWikiServices object.
114 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
116 public static function forceGlobalInstance( MediaWikiServices
$services ) {
117 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
118 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
121 $old = self
::getInstance();
122 self
::$instance = $services;
128 * Creates a new instance of MediaWikiServices and sets it as the global default
129 * instance. getInstance() will return a different MediaWikiServices object
130 * after every call to resetGlobalInstance().
134 * @warning This should not be used during normal operation. It is intended for use
135 * when the configuration has changed significantly since bootstrap time, e.g.
136 * during the installation process or during testing.
138 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
139 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
140 * any of the services managed by MediaWikiServices exist. If any service objects
141 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
142 * with the operation of the services managed by the new MediaWikiServices.
143 * Operating with a mix of services created by the old and the new
144 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
145 * Any class implementing LAZY LOADING is especially prone to this problem,
146 * since instances would typically retain a reference to a storage layer service.
148 * @see forceGlobalInstance()
149 * @see resetGlobalInstance()
150 * @see resetBetweenTest()
152 * @param Config|null $bootstrapConfig The Config object to be registered as the
153 * 'BootstrapConfig' service. This has to contain at least the information
154 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
155 * config of the old instance of MediaWikiServices will be re-used. If there
156 * was no previous instance, a new GlobalVarConfig object will be used to
157 * bootstrap the services.
159 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
160 * See SalvageableService for details.
162 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
163 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
166 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
167 if ( self
::$instance === null ) {
168 // no global instance yet, nothing to reset
172 self
::failIfResetNotAllowed( __METHOD__
);
174 if ( $bootstrapConfig === null ) {
175 $bootstrapConfig = self
::$instance->getBootstrapConfig();
178 $oldInstance = self
::$instance;
180 self
::$instance = self
::newInstance( $bootstrapConfig );
181 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
183 if ( $quick === 'quick' ) {
184 self
::$instance->salvage( $oldInstance );
186 $oldInstance->destroy();
192 * Salvages the state of any salvageable service instances in $other.
194 * @note $other will have been destroyed when salvage() returns.
196 * @param MediaWikiServices $other
198 private function salvage( self
$other ) {
199 foreach ( $this->getServiceNames() as $name ) {
200 $oldService = $other->peekService( $name );
202 if ( $oldService instanceof SalvageableService
) {
203 /** @var SalvageableService $newService */
204 $newService = $this->getService( $name );
205 $newService->salvage( $oldService );
213 * Creates a new MediaWikiServices instance and initializes it according to the
214 * given $bootstrapConfig. In particular, all wiring files defined in the
215 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
217 * @param Config|null $bootstrapConfig The Config object to be registered as the
218 * 'BootstrapConfig' service.
220 * @param string $loadWiring set this to 'load' to load the wiring files specified
221 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
223 * @return MediaWikiServices
224 * @throws MWException
225 * @throws \FatalError
227 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
228 $instance = new self( $bootstrapConfig );
230 // Load the default wiring from the specified files.
231 if ( $loadWiring === 'load' ) {
232 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
233 $instance->loadWiringFiles( $wiringFiles );
236 // Provide a traditional hook point to allow extensions to configure services.
237 Hooks
::run( 'MediaWikiServices', [ $instance ] );
243 * Disables all storage layer services. After calling this, any attempt to access the
244 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
249 * @warning This is intended for extreme situations only and should never be used
250 * while serving normal web requests. Legitimate use cases for this method include
251 * the installation process. Test fixtures may also use this, if the fixture relies
254 * @see resetGlobalInstance()
255 * @see resetChildProcessServices()
257 public static function disableStorageBackend() {
258 // TODO: also disable some Caches, JobQueues, etc
259 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
260 $services = self
::getInstance();
262 foreach ( $destroy as $name ) {
263 $services->disableService( $name );
266 ObjectCache
::clear();
270 * Resets any services that may have become stale after a child process
271 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
272 * to call this method from the parent process.
276 * @note This is intended for use in the context of process forking only!
278 * @see resetGlobalInstance()
279 * @see disableStorageBackend()
281 public static function resetChildProcessServices() {
282 // NOTE: for now, just reset everything. Since we don't know the interdependencies
283 // between services, we can't do this more selectively at this time.
284 self
::resetGlobalInstance();
286 // Child, reseed because there is no bug in PHP:
287 // http://bugs.php.net/bug.php?id=42465
288 mt_srand( getmypid() );
292 * Resets the given service for testing purposes.
296 * @warning This is generally unsafe! Other services may still retain references
297 * to the stale service instance, leading to failures and inconsistencies. Subclasses
298 * may use this method to reset specific services under specific instances, but
299 * it should not be exposed to application logic.
301 * @note With proper dependency injection used throughout the codebase, this method
302 * should not be needed. It is provided to allow tests that pollute global service
303 * instances to clean up.
305 * @param string $name
306 * @param bool $destroy Whether the service instance should be destroyed if it exists.
307 * When set to false, any existing service instance will effectively be detached
308 * from the container.
310 * @throws MWException if called outside of PHPUnit tests.
312 public function resetServiceForTesting( $name, $destroy = true ) {
313 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
314 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
317 $this->resetService( $name, $destroy );
321 * Convenience method that throws an exception unless it is called during a phase in which
322 * resetting of global services is allowed. In general, services should not be reset
323 * individually, since that may introduce inconsistencies.
327 * This method will throw an exception if:
329 * - self::$resetInProgress is false (to allow all services to be reset together
330 * via resetGlobalInstance)
331 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
332 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
334 * This method is intended to be used to safeguard against accidentally resetting
335 * global service instances that are not yet managed by MediaWikiServices. It is
336 * defined here in the MediaWikiServices services class to have a central place
337 * for managing service bootstrapping and resetting.
339 * @param string $method the name of the caller method, as given by __METHOD__.
341 * @throws MWException if called outside bootstrap mode.
343 * @see resetGlobalInstance()
344 * @see forceGlobalInstance()
345 * @see disableStorageBackend()
347 public static function failIfResetNotAllowed( $method ) {
348 if ( !defined( 'MW_PHPUNIT_TEST' )
349 && !defined( 'MW_PARSER_TEST' )
350 && !defined( 'MEDIAWIKI_INSTALL' )
351 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
352 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
354 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
359 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
360 * This has to contain at least the information needed to set up the 'ConfigFactory'
363 public function __construct( Config
$config ) {
364 parent
::__construct();
366 // Register the given Config object as the bootstrap config service.
367 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
372 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
375 * Returns the Config object containing the bootstrap configuration.
376 * Bootstrap configuration would typically include database credentials
377 * and other information that may be needed before the ConfigFactory
378 * service can be instantiated.
380 * @note This should only be used during bootstrapping, in particular
381 * when creating the MainConfig service. Application logic should
382 * use getMainConfig() to get a Config instances.
387 public function getBootstrapConfig() {
388 return $this->getService( 'BootstrapConfig' );
393 * @return ConfigFactory
395 public function getConfigFactory() {
396 return $this->getService( 'ConfigFactory' );
400 * Returns the Config object that provides configuration for MediaWiki core.
401 * This may or may not be the same object that is returned by getBootstrapConfig().
406 public function getMainConfig() {
407 return $this->getService( 'MainConfig' );
414 public function getSiteLookup() {
415 return $this->getService( 'SiteLookup' );
422 public function getSiteStore() {
423 return $this->getService( 'SiteStore' );
428 * @return InterwikiLookup
430 public function getInterwikiLookup() {
431 return $this->getService( 'InterwikiLookup' );
436 * @return StatsdDataFactory
438 public function getStatsdDataFactory() {
439 return $this->getService( 'StatsdDataFactory' );
444 * @return EventRelayerGroup
446 public function getEventRelayerGroup() {
447 return $this->getService( 'EventRelayerGroup' );
452 * @return SearchEngine
454 public function newSearchEngine() {
455 // New engine object every time, since they keep state
456 return $this->getService( 'SearchEngineFactory' )->create();
461 * @return SearchEngineFactory
463 public function getSearchEngineFactory() {
464 return $this->getService( 'SearchEngineFactory' );
469 * @return SearchEngineConfig
471 public function getSearchEngineConfig() {
472 return $this->getService( 'SearchEngineConfig' );
477 * @return SkinFactory
479 public function getSkinFactory() {
480 return $this->getService( 'SkinFactory' );
487 public function getDBLoadBalancerFactory() {
488 return $this->getService( 'DBLoadBalancerFactory' );
493 * @return LoadBalancer The main DB load balancer for the local wiki.
495 public function getDBLoadBalancer() {
496 return $this->getService( 'DBLoadBalancer' );
501 * @return WatchedItemStore
503 public function getWatchedItemStore() {
504 return $this->getService( 'WatchedItemStore' );
509 * @return WatchedItemQueryService
511 public function getWatchedItemQueryService() {
512 return $this->getService( 'WatchedItemQueryService' );
517 * @return MediaHandlerFactory
519 public function getMediaHandlerFactory() {
520 return $this->getService( 'MediaHandlerFactory' );
525 * @return GenderCache
527 public function getGenderCache() {
528 return $this->getService( 'GenderCache' );
535 public function getLinkCache() {
536 return $this->getService( 'LinkCache' );
541 * @return LinkRendererFactory
543 public function getLinkRendererFactory() {
544 return $this->getService( 'LinkRendererFactory' );
548 * LinkRenderer instance that can be used
549 * if no custom options are needed
552 * @return LinkRenderer
554 public function getLinkRenderer() {
555 return $this->getService( 'LinkRenderer' );
560 * @return TitleFormatter
562 public function getTitleFormatter() {
563 return $this->getService( 'TitleFormatter' );
568 * @return TitleParser
570 public function getTitleParser() {
571 return $this->getService( 'TitleParser' );
574 ///////////////////////////////////////////////////////////////////////////
575 // NOTE: When adding a service getter here, don't forget to add a test
576 // case for it in MediaWikiServicesTest::provideGetters() and in
577 // MediaWikiServicesTest::provideGetService()!
578 ///////////////////////////////////////////////////////////////////////////