11 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
13 use MediaWiki\Services\SalvageableService
;
14 use MediaWiki\Services\ServiceContainer
;
18 use SearchEngineConfig
;
19 use SearchEngineFactory
;
28 * Service locator for MediaWiki core services.
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2 of the License, or
33 * (at your option) any later version.
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
40 * You should have received a copy of the GNU General Public License along
41 * with this program; if not, write to the Free Software Foundation, Inc.,
42 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
43 * http://www.gnu.org/copyleft/gpl.html
51 * MediaWikiServices is the service locator for the application scope of MediaWiki.
52 * Its implemented as a simple configurable DI container.
53 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
54 * the network of service objects that defines MediaWiki's application logic.
55 * It acts as an entry point to MediaWiki's dependency injection mechanism.
57 * Services are defined in the "wiring" array passed to the constructor,
58 * or by calling defineService().
60 * @see docs/injection.txt for an overview of using dependency injection in the
61 * MediaWiki code base.
63 class MediaWikiServices
extends ServiceContainer
{
66 * @var MediaWikiServices|null
68 private static $instance = null;
71 * Returns the global default instance of the top level service locator.
75 * The default instance is initialized using the service instantiator functions
76 * defined in ServiceWiring.php.
78 * @note This should only be called by static functions! The instance returned here
79 * should not be passed around! Objects that need access to a service should have
80 * that service injected into the constructor, never a service locator!
82 * @return MediaWikiServices
84 public static function getInstance() {
85 if ( self
::$instance === null ) {
86 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
87 // but some information from the global scope has to be injected here,
88 // even if it's just a file name or database credentials to load
89 // configuration from.
90 $bootstrapConfig = new GlobalVarConfig();
91 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
94 return self
::$instance;
98 * Replaces the global MediaWikiServices instance.
102 * @note This is for use in PHPUnit tests only!
104 * @throws MWException if called outside of PHPUnit tests.
106 * @param MediaWikiServices $services The new MediaWikiServices object.
108 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
110 public static function forceGlobalInstance( MediaWikiServices
$services ) {
111 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
112 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
115 $old = self
::getInstance();
116 self
::$instance = $services;
122 * Creates a new instance of MediaWikiServices and sets it as the global default
123 * instance. getInstance() will return a different MediaWikiServices object
124 * after every call to resetGlobalInstance().
128 * @warning This should not be used during normal operation. It is intended for use
129 * when the configuration has changed significantly since bootstrap time, e.g.
130 * during the installation process or during testing.
132 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
133 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
134 * any of the services managed by MediaWikiServices exist. If any service objects
135 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
136 * with the operation of the services managed by the new MediaWikiServices.
137 * Operating with a mix of services created by the old and the new
138 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
139 * Any class implementing LAZY LOADING is especially prone to this problem,
140 * since instances would typically retain a reference to a storage layer service.
142 * @see forceGlobalInstance()
143 * @see resetGlobalInstance()
144 * @see resetBetweenTest()
146 * @param Config|null $bootstrapConfig The Config object to be registered as the
147 * 'BootstrapConfig' service. This has to contain at least the information
148 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
149 * config of the old instance of MediaWikiServices will be re-used. If there
150 * was no previous instance, a new GlobalVarConfig object will be used to
151 * bootstrap the services.
153 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
154 * See SalvageableService for details.
156 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
157 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
160 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
161 if ( self
::$instance === null ) {
162 // no global instance yet, nothing to reset
166 self
::failIfResetNotAllowed( __METHOD__
);
168 if ( $bootstrapConfig === null ) {
169 $bootstrapConfig = self
::$instance->getBootstrapConfig();
172 $oldInstance = self
::$instance;
174 self
::$instance = self
::newInstance( $bootstrapConfig );
175 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
177 if ( $quick === 'quick' ) {
178 self
::$instance->salvage( $oldInstance );
180 $oldInstance->destroy();
186 * Salvages the state of any salvageable service instances in $other.
188 * @note $other will have been destroyed when salvage() returns.
190 * @param MediaWikiServices $other
192 private function salvage( self
$other ) {
193 foreach ( $this->getServiceNames() as $name ) {
194 $oldService = $other->peekService( $name );
196 if ( $oldService instanceof SalvageableService
) {
197 /** @var SalvageableService $newService */
198 $newService = $this->getService( $name );
199 $newService->salvage( $oldService );
207 * Creates a new MediaWikiServices instance and initializes it according to the
208 * given $bootstrapConfig. In particular, all wiring files defined in the
209 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
211 * @param Config|null $bootstrapConfig The Config object to be registered as the
212 * 'BootstrapConfig' service.
214 * @param string $loadWiring set this to 'load' to load the wiring files specified
215 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
217 * @return MediaWikiServices
218 * @throws MWException
219 * @throws \FatalError
221 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
222 $instance = new self( $bootstrapConfig );
224 // Load the default wiring from the specified files.
225 if ( $loadWiring === 'load' ) {
226 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
227 $instance->loadWiringFiles( $wiringFiles );
230 // Provide a traditional hook point to allow extensions to configure services.
231 Hooks
::run( 'MediaWikiServices', [ $instance ] );
237 * Disables all storage layer services. After calling this, any attempt to access the
238 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
243 * @warning This is intended for extreme situations only and should never be used
244 * while serving normal web requests. Legitimate use cases for this method include
245 * the installation process. Test fixtures may also use this, if the fixture relies
248 * @see resetGlobalInstance()
249 * @see resetChildProcessServices()
251 public static function disableStorageBackend() {
252 // TODO: also disable some Caches, JobQueues, etc
253 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
254 $services = self
::getInstance();
256 foreach ( $destroy as $name ) {
257 $services->disableService( $name );
262 * Resets any services that may have become stale after a child process
263 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
264 * to call this method from the parent process.
268 * @note This is intended for use in the context of process forking only!
270 * @see resetGlobalInstance()
271 * @see disableStorageBackend()
273 public static function resetChildProcessServices() {
274 // NOTE: for now, just reset everything. Since we don't know the interdependencies
275 // between services, we can't do this more selectively at this time.
276 self
::resetGlobalInstance();
278 // Child, reseed because there is no bug in PHP:
279 // http://bugs.php.net/bug.php?id=42465
280 mt_srand( getmypid() );
284 * Resets the given service for testing purposes.
288 * @warning This is generally unsafe! Other services may still retain references
289 * to the stale service instance, leading to failures and inconsistencies. Subclasses
290 * may use this method to reset specific services under specific instances, but
291 * it should not be exposed to application logic.
293 * @note With proper dependency injection used throughout the codebase, this method
294 * should not be needed. It is provided to allow tests that pollute global service
295 * instances to clean up.
297 * @param string $name
298 * @param string $destroy Whether the service instance should be destroyed if it exists.
299 * When set to false, any existing service instance will effectively be detached
300 * from the container.
302 * @throws MWException if called outside of PHPUnit tests.
304 public function resetServiceForTesting( $name, $destroy = true ) {
305 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
306 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
309 $this->resetService( $name, $destroy );
313 * Convenience method that throws an exception unless it is called during a phase in which
314 * resetting of global services is allowed. In general, services should not be reset
315 * individually, since that may introduce inconsistencies.
319 * This method will throw an exception if:
321 * - self::$resetInProgress is false (to allow all services to be reset together
322 * via resetGlobalInstance)
323 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
324 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
326 * This method is intended to be used to safeguard against accidentally resetting
327 * global service instances that are not yet managed by MediaWikiServices. It is
328 * defined here in the MediaWikiServices services class to have a central place
329 * for managing service bootstrapping and resetting.
331 * @param string $method the name of the caller method, as given by __METHOD__.
333 * @throws MWException if called outside bootstrap mode.
335 * @see resetGlobalInstance()
336 * @see forceGlobalInstance()
337 * @see disableStorageBackend()
339 public static function failIfResetNotAllowed( $method ) {
340 if ( !defined( 'MW_PHPUNIT_TEST' )
341 && !defined( 'MW_PARSER_TEST' )
342 && !defined( 'MEDIAWIKI_INSTALL' )
343 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
344 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
346 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
351 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
352 * This has to contain at least the information needed to set up the 'ConfigFactory'
355 public function __construct( Config
$config ) {
356 parent
::__construct();
358 // Register the given Config object as the bootstrap config service.
359 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
364 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
367 * Returns the Config object containing the bootstrap configuration.
368 * Bootstrap configuration would typically include database credentials
369 * and other information that may be needed before the ConfigFactory
370 * service can be instantiated.
372 * @note This should only be used during bootstrapping, in particular
373 * when creating the MainConfig service. Application logic should
374 * use getMainConfig() to get a Config instances.
379 public function getBootstrapConfig() {
380 return $this->getService( 'BootstrapConfig' );
385 * @return ConfigFactory
387 public function getConfigFactory() {
388 return $this->getService( 'ConfigFactory' );
392 * Returns the Config object that provides configuration for MediaWiki core.
393 * This may or may not be the same object that is returned by getBootstrapConfig().
398 public function getMainConfig() {
399 return $this->getService( 'MainConfig' );
406 public function getSiteLookup() {
407 return $this->getService( 'SiteLookup' );
414 public function getSiteStore() {
415 return $this->getService( 'SiteStore' );
420 * @return StatsdDataFactory
422 public function getStatsdDataFactory() {
423 return $this->getService( 'StatsdDataFactory' );
428 * @return EventRelayerGroup
430 public function getEventRelayerGroup() {
431 return $this->getService( 'EventRelayerGroup' );
436 * @return SearchEngine
438 public function newSearchEngine() {
439 // New engine object every time, since they keep state
440 return $this->getService( 'SearchEngineFactory' )->create();
445 * @return SearchEngineFactory
447 public function getSearchEngineFactory() {
448 return $this->getService( 'SearchEngineFactory' );
453 * @return SearchEngineConfig
455 public function getSearchEngineConfig() {
456 return $this->getService( 'SearchEngineConfig' );
461 * @return SkinFactory
463 public function getSkinFactory() {
464 return $this->getService( 'SkinFactory' );
471 public function getDBLoadBalancerFactory() {
472 return $this->getService( 'DBLoadBalancerFactory' );
477 * @return LoadBalancer The main DB load balancer for the local wiki.
479 public function getDBLoadBalancer() {
480 return $this->getService( 'DBLoadBalancer' );
485 * @return WatchedItemStore
487 public function getWatchedItemStore() {
488 return $this->getService( 'WatchedItemStore' );
493 * @return GenderCache
495 public function getGenderCache() {
496 return $this->getService( 'GenderCache' );
500 * @return TitleFormatter
502 public function getTitleFormatter() {
503 return $this->getService( 'TitleFormatter' );
508 * @return TitleParser
510 public function getTitleParser() {
511 return $this->getService( 'TitleParser' );
514 ///////////////////////////////////////////////////////////////////////////
515 // NOTE: When adding a service getter here, don't forget to add a test
516 // case for it in MediaWikiServicesTest::provideGetters() and in
517 // MediaWikiServicesTest::provideGetService()!
518 ///////////////////////////////////////////////////////////////////////////