12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
14 use MediaWiki\Services\SalvageableService
;
15 use MediaWiki\Services\ServiceContainer
;
19 use SearchEngineConfig
;
20 use SearchEngineFactory
;
27 use MediaWiki\Interwiki\InterwikiLookup
;
30 * Service locator for MediaWiki core services.
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 2 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License along
43 * with this program; if not, write to the Free Software Foundation, Inc.,
44 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
45 * http://www.gnu.org/copyleft/gpl.html
53 * MediaWikiServices is the service locator for the application scope of MediaWiki.
54 * Its implemented as a simple configurable DI container.
55 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
56 * the network of service objects that defines MediaWiki's application logic.
57 * It acts as an entry point to MediaWiki's dependency injection mechanism.
59 * Services are defined in the "wiring" array passed to the constructor,
60 * or by calling defineService().
62 * @see docs/injection.txt for an overview of using dependency injection in the
63 * MediaWiki code base.
65 class MediaWikiServices
extends ServiceContainer
{
68 * @var MediaWikiServices|null
70 private static $instance = null;
73 * Returns the global default instance of the top level service locator.
77 * The default instance is initialized using the service instantiator functions
78 * defined in ServiceWiring.php.
80 * @note This should only be called by static functions! The instance returned here
81 * should not be passed around! Objects that need access to a service should have
82 * that service injected into the constructor, never a service locator!
84 * @return MediaWikiServices
86 public static function getInstance() {
87 if ( self
::$instance === null ) {
88 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
89 // but some information from the global scope has to be injected here,
90 // even if it's just a file name or database credentials to load
91 // configuration from.
92 $bootstrapConfig = new GlobalVarConfig();
93 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
96 return self
::$instance;
100 * Replaces the global MediaWikiServices instance.
104 * @note This is for use in PHPUnit tests only!
106 * @throws MWException if called outside of PHPUnit tests.
108 * @param MediaWikiServices $services The new MediaWikiServices object.
110 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
112 public static function forceGlobalInstance( MediaWikiServices
$services ) {
113 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
114 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
117 $old = self
::getInstance();
118 self
::$instance = $services;
124 * Creates a new instance of MediaWikiServices and sets it as the global default
125 * instance. getInstance() will return a different MediaWikiServices object
126 * after every call to resetGlobalInstance().
130 * @warning This should not be used during normal operation. It is intended for use
131 * when the configuration has changed significantly since bootstrap time, e.g.
132 * during the installation process or during testing.
134 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
135 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
136 * any of the services managed by MediaWikiServices exist. If any service objects
137 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
138 * with the operation of the services managed by the new MediaWikiServices.
139 * Operating with a mix of services created by the old and the new
140 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
141 * Any class implementing LAZY LOADING is especially prone to this problem,
142 * since instances would typically retain a reference to a storage layer service.
144 * @see forceGlobalInstance()
145 * @see resetGlobalInstance()
146 * @see resetBetweenTest()
148 * @param Config|null $bootstrapConfig The Config object to be registered as the
149 * 'BootstrapConfig' service. This has to contain at least the information
150 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
151 * config of the old instance of MediaWikiServices will be re-used. If there
152 * was no previous instance, a new GlobalVarConfig object will be used to
153 * bootstrap the services.
155 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
156 * See SalvageableService for details.
158 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
159 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
162 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
163 if ( self
::$instance === null ) {
164 // no global instance yet, nothing to reset
168 self
::failIfResetNotAllowed( __METHOD__
);
170 if ( $bootstrapConfig === null ) {
171 $bootstrapConfig = self
::$instance->getBootstrapConfig();
174 $oldInstance = self
::$instance;
176 self
::$instance = self
::newInstance( $bootstrapConfig );
177 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
179 if ( $quick === 'quick' ) {
180 self
::$instance->salvage( $oldInstance );
182 $oldInstance->destroy();
188 * Salvages the state of any salvageable service instances in $other.
190 * @note $other will have been destroyed when salvage() returns.
192 * @param MediaWikiServices $other
194 private function salvage( self
$other ) {
195 foreach ( $this->getServiceNames() as $name ) {
196 $oldService = $other->peekService( $name );
198 if ( $oldService instanceof SalvageableService
) {
199 /** @var SalvageableService $newService */
200 $newService = $this->getService( $name );
201 $newService->salvage( $oldService );
209 * Creates a new MediaWikiServices instance and initializes it according to the
210 * given $bootstrapConfig. In particular, all wiring files defined in the
211 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
213 * @param Config|null $bootstrapConfig The Config object to be registered as the
214 * 'BootstrapConfig' service.
216 * @param string $loadWiring set this to 'load' to load the wiring files specified
217 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
219 * @return MediaWikiServices
220 * @throws MWException
221 * @throws \FatalError
223 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
224 $instance = new self( $bootstrapConfig );
226 // Load the default wiring from the specified files.
227 if ( $loadWiring === 'load' ) {
228 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
229 $instance->loadWiringFiles( $wiringFiles );
232 // Provide a traditional hook point to allow extensions to configure services.
233 Hooks
::run( 'MediaWikiServices', [ $instance ] );
239 * Disables all storage layer services. After calling this, any attempt to access the
240 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
245 * @warning This is intended for extreme situations only and should never be used
246 * while serving normal web requests. Legitimate use cases for this method include
247 * the installation process. Test fixtures may also use this, if the fixture relies
250 * @see resetGlobalInstance()
251 * @see resetChildProcessServices()
253 public static function disableStorageBackend() {
254 // TODO: also disable some Caches, JobQueues, etc
255 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
256 $services = self
::getInstance();
258 foreach ( $destroy as $name ) {
259 $services->disableService( $name );
262 ObjectCache
::clear();
266 * Resets any services that may have become stale after a child process
267 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
268 * to call this method from the parent process.
272 * @note This is intended for use in the context of process forking only!
274 * @see resetGlobalInstance()
275 * @see disableStorageBackend()
277 public static function resetChildProcessServices() {
278 // NOTE: for now, just reset everything. Since we don't know the interdependencies
279 // between services, we can't do this more selectively at this time.
280 self
::resetGlobalInstance();
282 // Child, reseed because there is no bug in PHP:
283 // http://bugs.php.net/bug.php?id=42465
284 mt_srand( getmypid() );
288 * Resets the given service for testing purposes.
292 * @warning This is generally unsafe! Other services may still retain references
293 * to the stale service instance, leading to failures and inconsistencies. Subclasses
294 * may use this method to reset specific services under specific instances, but
295 * it should not be exposed to application logic.
297 * @note With proper dependency injection used throughout the codebase, this method
298 * should not be needed. It is provided to allow tests that pollute global service
299 * instances to clean up.
301 * @param string $name
302 * @param bool $destroy Whether the service instance should be destroyed if it exists.
303 * When set to false, any existing service instance will effectively be detached
304 * from the container.
306 * @throws MWException if called outside of PHPUnit tests.
308 public function resetServiceForTesting( $name, $destroy = true ) {
309 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
310 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
313 $this->resetService( $name, $destroy );
317 * Convenience method that throws an exception unless it is called during a phase in which
318 * resetting of global services is allowed. In general, services should not be reset
319 * individually, since that may introduce inconsistencies.
323 * This method will throw an exception if:
325 * - self::$resetInProgress is false (to allow all services to be reset together
326 * via resetGlobalInstance)
327 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
328 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
330 * This method is intended to be used to safeguard against accidentally resetting
331 * global service instances that are not yet managed by MediaWikiServices. It is
332 * defined here in the MediaWikiServices services class to have a central place
333 * for managing service bootstrapping and resetting.
335 * @param string $method the name of the caller method, as given by __METHOD__.
337 * @throws MWException if called outside bootstrap mode.
339 * @see resetGlobalInstance()
340 * @see forceGlobalInstance()
341 * @see disableStorageBackend()
343 public static function failIfResetNotAllowed( $method ) {
344 if ( !defined( 'MW_PHPUNIT_TEST' )
345 && !defined( 'MW_PARSER_TEST' )
346 && !defined( 'MEDIAWIKI_INSTALL' )
347 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
348 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
350 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
355 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
356 * This has to contain at least the information needed to set up the 'ConfigFactory'
359 public function __construct( Config
$config ) {
360 parent
::__construct();
362 // Register the given Config object as the bootstrap config service.
363 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
368 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
371 * Returns the Config object containing the bootstrap configuration.
372 * Bootstrap configuration would typically include database credentials
373 * and other information that may be needed before the ConfigFactory
374 * service can be instantiated.
376 * @note This should only be used during bootstrapping, in particular
377 * when creating the MainConfig service. Application logic should
378 * use getMainConfig() to get a Config instances.
383 public function getBootstrapConfig() {
384 return $this->getService( 'BootstrapConfig' );
389 * @return ConfigFactory
391 public function getConfigFactory() {
392 return $this->getService( 'ConfigFactory' );
396 * Returns the Config object that provides configuration for MediaWiki core.
397 * This may or may not be the same object that is returned by getBootstrapConfig().
402 public function getMainConfig() {
403 return $this->getService( 'MainConfig' );
410 public function getSiteLookup() {
411 return $this->getService( 'SiteLookup' );
418 public function getSiteStore() {
419 return $this->getService( 'SiteStore' );
424 * @return InterwikiLookup
426 public function getInterwikiLookup() {
427 return $this->getService( 'InterwikiLookup' );
432 * @return StatsdDataFactory
434 public function getStatsdDataFactory() {
435 return $this->getService( 'StatsdDataFactory' );
440 * @return EventRelayerGroup
442 public function getEventRelayerGroup() {
443 return $this->getService( 'EventRelayerGroup' );
448 * @return SearchEngine
450 public function newSearchEngine() {
451 // New engine object every time, since they keep state
452 return $this->getService( 'SearchEngineFactory' )->create();
457 * @return SearchEngineFactory
459 public function getSearchEngineFactory() {
460 return $this->getService( 'SearchEngineFactory' );
465 * @return SearchEngineConfig
467 public function getSearchEngineConfig() {
468 return $this->getService( 'SearchEngineConfig' );
473 * @return SkinFactory
475 public function getSkinFactory() {
476 return $this->getService( 'SkinFactory' );
483 public function getDBLoadBalancerFactory() {
484 return $this->getService( 'DBLoadBalancerFactory' );
489 * @return LoadBalancer The main DB load balancer for the local wiki.
491 public function getDBLoadBalancer() {
492 return $this->getService( 'DBLoadBalancer' );
497 * @return WatchedItemStore
499 public function getWatchedItemStore() {
500 return $this->getService( 'WatchedItemStore' );
505 * @return GenderCache
507 public function getGenderCache() {
508 return $this->getService( 'GenderCache' );
515 public function getLinkCache() {
516 return $this->getService( 'LinkCache' );
521 * @return TitleFormatter
523 public function getTitleFormatter() {
524 return $this->getService( 'TitleFormatter' );
529 * @return TitleParser
531 public function getTitleParser() {
532 return $this->getService( 'TitleParser' );
535 ///////////////////////////////////////////////////////////////////////////
536 // NOTE: When adding a service getter here, don't forget to add a test
537 // case for it in MediaWikiServicesTest::provideGetters() and in
538 // MediaWikiServicesTest::provideGetService()!
539 ///////////////////////////////////////////////////////////////////////////