12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
14 use MediaWiki\Services\SalvageableService
;
15 use MediaWiki\Services\ServiceContainer
;
20 use SearchEngineConfig
;
21 use SearchEngineFactory
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
31 * Service locator for MediaWiki core services.
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License along
44 * with this program; if not, write to the Free Software Foundation, Inc.,
45 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
46 * http://www.gnu.org/copyleft/gpl.html
54 * MediaWikiServices is the service locator for the application scope of MediaWiki.
55 * Its implemented as a simple configurable DI container.
56 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
57 * the network of service objects that defines MediaWiki's application logic.
58 * It acts as an entry point to MediaWiki's dependency injection mechanism.
60 * Services are defined in the "wiring" array passed to the constructor,
61 * or by calling defineService().
63 * @see docs/injection.txt for an overview of using dependency injection in the
64 * MediaWiki code base.
66 class MediaWikiServices
extends ServiceContainer
{
69 * @var MediaWikiServices|null
71 private static $instance = null;
74 * Returns the global default instance of the top level service locator.
78 * The default instance is initialized using the service instantiator functions
79 * defined in ServiceWiring.php.
81 * @note This should only be called by static functions! The instance returned here
82 * should not be passed around! Objects that need access to a service should have
83 * that service injected into the constructor, never a service locator!
85 * @return MediaWikiServices
87 public static function getInstance() {
88 if ( self
::$instance === null ) {
89 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
90 // but some information from the global scope has to be injected here,
91 // even if it's just a file name or database credentials to load
92 // configuration from.
93 $bootstrapConfig = new GlobalVarConfig();
94 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
97 return self
::$instance;
101 * Replaces the global MediaWikiServices instance.
105 * @note This is for use in PHPUnit tests only!
107 * @throws MWException if called outside of PHPUnit tests.
109 * @param MediaWikiServices $services The new MediaWikiServices object.
111 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
113 public static function forceGlobalInstance( MediaWikiServices
$services ) {
114 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
115 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
118 $old = self
::getInstance();
119 self
::$instance = $services;
125 * Creates a new instance of MediaWikiServices and sets it as the global default
126 * instance. getInstance() will return a different MediaWikiServices object
127 * after every call to resetGlobalInstance().
131 * @warning This should not be used during normal operation. It is intended for use
132 * when the configuration has changed significantly since bootstrap time, e.g.
133 * during the installation process or during testing.
135 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
136 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
137 * any of the services managed by MediaWikiServices exist. If any service objects
138 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
139 * with the operation of the services managed by the new MediaWikiServices.
140 * Operating with a mix of services created by the old and the new
141 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
142 * Any class implementing LAZY LOADING is especially prone to this problem,
143 * since instances would typically retain a reference to a storage layer service.
145 * @see forceGlobalInstance()
146 * @see resetGlobalInstance()
147 * @see resetBetweenTest()
149 * @param Config|null $bootstrapConfig The Config object to be registered as the
150 * 'BootstrapConfig' service. This has to contain at least the information
151 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
152 * config of the old instance of MediaWikiServices will be re-used. If there
153 * was no previous instance, a new GlobalVarConfig object will be used to
154 * bootstrap the services.
156 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
157 * See SalvageableService for details.
159 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
160 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
163 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
164 if ( self
::$instance === null ) {
165 // no global instance yet, nothing to reset
169 self
::failIfResetNotAllowed( __METHOD__
);
171 if ( $bootstrapConfig === null ) {
172 $bootstrapConfig = self
::$instance->getBootstrapConfig();
175 $oldInstance = self
::$instance;
177 self
::$instance = self
::newInstance( $bootstrapConfig );
178 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
180 if ( $quick === 'quick' ) {
181 self
::$instance->salvage( $oldInstance );
183 $oldInstance->destroy();
189 * Salvages the state of any salvageable service instances in $other.
191 * @note $other will have been destroyed when salvage() returns.
193 * @param MediaWikiServices $other
195 private function salvage( self
$other ) {
196 foreach ( $this->getServiceNames() as $name ) {
197 $oldService = $other->peekService( $name );
199 if ( $oldService instanceof SalvageableService
) {
200 /** @var SalvageableService $newService */
201 $newService = $this->getService( $name );
202 $newService->salvage( $oldService );
210 * Creates a new MediaWikiServices instance and initializes it according to the
211 * given $bootstrapConfig. In particular, all wiring files defined in the
212 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
214 * @param Config|null $bootstrapConfig The Config object to be registered as the
215 * 'BootstrapConfig' service.
217 * @param string $loadWiring set this to 'load' to load the wiring files specified
218 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
220 * @return MediaWikiServices
221 * @throws MWException
222 * @throws \FatalError
224 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
225 $instance = new self( $bootstrapConfig );
227 // Load the default wiring from the specified files.
228 if ( $loadWiring === 'load' ) {
229 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
230 $instance->loadWiringFiles( $wiringFiles );
233 // Provide a traditional hook point to allow extensions to configure services.
234 Hooks
::run( 'MediaWikiServices', [ $instance ] );
240 * Disables all storage layer services. After calling this, any attempt to access the
241 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
246 * @warning This is intended for extreme situations only and should never be used
247 * while serving normal web requests. Legitimate use cases for this method include
248 * the installation process. Test fixtures may also use this, if the fixture relies
251 * @see resetGlobalInstance()
252 * @see resetChildProcessServices()
254 public static function disableStorageBackend() {
255 // TODO: also disable some Caches, JobQueues, etc
256 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
257 $services = self
::getInstance();
259 foreach ( $destroy as $name ) {
260 $services->disableService( $name );
263 ObjectCache
::clear();
267 * Resets any services that may have become stale after a child process
268 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
269 * to call this method from the parent process.
273 * @note This is intended for use in the context of process forking only!
275 * @see resetGlobalInstance()
276 * @see disableStorageBackend()
278 public static function resetChildProcessServices() {
279 // NOTE: for now, just reset everything. Since we don't know the interdependencies
280 // between services, we can't do this more selectively at this time.
281 self
::resetGlobalInstance();
283 // Child, reseed because there is no bug in PHP:
284 // http://bugs.php.net/bug.php?id=42465
285 mt_srand( getmypid() );
289 * Resets the given service for testing purposes.
293 * @warning This is generally unsafe! Other services may still retain references
294 * to the stale service instance, leading to failures and inconsistencies. Subclasses
295 * may use this method to reset specific services under specific instances, but
296 * it should not be exposed to application logic.
298 * @note With proper dependency injection used throughout the codebase, this method
299 * should not be needed. It is provided to allow tests that pollute global service
300 * instances to clean up.
302 * @param string $name
303 * @param bool $destroy Whether the service instance should be destroyed if it exists.
304 * When set to false, any existing service instance will effectively be detached
305 * from the container.
307 * @throws MWException if called outside of PHPUnit tests.
309 public function resetServiceForTesting( $name, $destroy = true ) {
310 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
311 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
314 $this->resetService( $name, $destroy );
318 * Convenience method that throws an exception unless it is called during a phase in which
319 * resetting of global services is allowed. In general, services should not be reset
320 * individually, since that may introduce inconsistencies.
324 * This method will throw an exception if:
326 * - self::$resetInProgress is false (to allow all services to be reset together
327 * via resetGlobalInstance)
328 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
329 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
331 * This method is intended to be used to safeguard against accidentally resetting
332 * global service instances that are not yet managed by MediaWikiServices. It is
333 * defined here in the MediaWikiServices services class to have a central place
334 * for managing service bootstrapping and resetting.
336 * @param string $method the name of the caller method, as given by __METHOD__.
338 * @throws MWException if called outside bootstrap mode.
340 * @see resetGlobalInstance()
341 * @see forceGlobalInstance()
342 * @see disableStorageBackend()
344 public static function failIfResetNotAllowed( $method ) {
345 if ( !defined( 'MW_PHPUNIT_TEST' )
346 && !defined( 'MW_PARSER_TEST' )
347 && !defined( 'MEDIAWIKI_INSTALL' )
348 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
349 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
351 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
356 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
357 * This has to contain at least the information needed to set up the 'ConfigFactory'
360 public function __construct( Config
$config ) {
361 parent
::__construct();
363 // Register the given Config object as the bootstrap config service.
364 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
369 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
372 * Returns the Config object containing the bootstrap configuration.
373 * Bootstrap configuration would typically include database credentials
374 * and other information that may be needed before the ConfigFactory
375 * service can be instantiated.
377 * @note This should only be used during bootstrapping, in particular
378 * when creating the MainConfig service. Application logic should
379 * use getMainConfig() to get a Config instances.
384 public function getBootstrapConfig() {
385 return $this->getService( 'BootstrapConfig' );
390 * @return ConfigFactory
392 public function getConfigFactory() {
393 return $this->getService( 'ConfigFactory' );
397 * Returns the Config object that provides configuration for MediaWiki core.
398 * This may or may not be the same object that is returned by getBootstrapConfig().
403 public function getMainConfig() {
404 return $this->getService( 'MainConfig' );
411 public function getSiteLookup() {
412 return $this->getService( 'SiteLookup' );
419 public function getSiteStore() {
420 return $this->getService( 'SiteStore' );
425 * @return InterwikiLookup
427 public function getInterwikiLookup() {
428 return $this->getService( 'InterwikiLookup' );
433 * @return StatsdDataFactory
435 public function getStatsdDataFactory() {
436 return $this->getService( 'StatsdDataFactory' );
441 * @return EventRelayerGroup
443 public function getEventRelayerGroup() {
444 return $this->getService( 'EventRelayerGroup' );
449 * @return SearchEngine
451 public function newSearchEngine() {
452 // New engine object every time, since they keep state
453 return $this->getService( 'SearchEngineFactory' )->create();
458 * @return SearchEngineFactory
460 public function getSearchEngineFactory() {
461 return $this->getService( 'SearchEngineFactory' );
466 * @return SearchEngineConfig
468 public function getSearchEngineConfig() {
469 return $this->getService( 'SearchEngineConfig' );
474 * @return SkinFactory
476 public function getSkinFactory() {
477 return $this->getService( 'SkinFactory' );
484 public function getDBLoadBalancerFactory() {
485 return $this->getService( 'DBLoadBalancerFactory' );
490 * @return LoadBalancer The main DB load balancer for the local wiki.
492 public function getDBLoadBalancer() {
493 return $this->getService( 'DBLoadBalancer' );
498 * @return WatchedItemStore
500 public function getWatchedItemStore() {
501 return $this->getService( 'WatchedItemStore' );
506 * @return GenderCache
508 public function getGenderCache() {
509 return $this->getService( 'GenderCache' );
516 public function getLinkCache() {
517 return $this->getService( 'LinkCache' );
522 * @return TitleFormatter
524 public function getTitleFormatter() {
525 return $this->getService( 'TitleFormatter' );
530 * @return TitleParser
532 public function getTitleParser() {
533 return $this->getService( 'TitleParser' );
536 ///////////////////////////////////////////////////////////////////////////
537 // NOTE: When adding a service getter here, don't forget to add a test
538 // case for it in MediaWikiServicesTest::provideGetters() and in
539 // MediaWikiServicesTest::provideGetService()!
540 ///////////////////////////////////////////////////////////////////////////