12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
14 use MediaWiki\Services\ServiceContainer
;
19 use SearchEngineConfig
;
20 use SearchEngineFactory
;
29 * Service locator for MediaWiki core services.
31 * This program is free software; you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation; either version 2 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License along
42 * with this program; if not, write to the Free Software Foundation, Inc.,
43 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
44 * http://www.gnu.org/copyleft/gpl.html
52 * MediaWikiServices is the service locator for the application scope of MediaWiki.
53 * Its implemented as a simple configurable DI container.
54 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
55 * the network of service objects that defines MediaWiki's application logic.
56 * It acts as an entry point to MediaWiki's dependency injection mechanism.
58 * Services are defined in the "wiring" array passed to the constructor,
59 * or by calling defineService().
61 * @see docs/injection.txt for an overview of using dependency injection in the
62 * MediaWiki code base.
64 class MediaWikiServices
extends ServiceContainer
{
67 * @var MediaWikiServices|null
69 private static $instance = null;
72 * Returns the global default instance of the top level service locator.
76 * The default instance is initialized using the service instantiator functions
77 * defined in ServiceWiring.php.
79 * @note This should only be called by static functions! The instance returned here
80 * should not be passed around! Objects that need access to a service should have
81 * that service injected into the constructor, never a service locator!
83 * @return MediaWikiServices
85 public static function getInstance() {
86 if ( self
::$instance === null ) {
87 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
88 // but some information from the global scope has to be injected here,
89 // even if it's just a file name or database credentials to load
90 // configuration from.
91 $bootstrapConfig = new GlobalVarConfig();
92 self
::$instance = self
::newInstance( $bootstrapConfig );
95 return self
::$instance;
99 * Replaces the global MediaWikiServices instance.
103 * @note This is for use in PHPUnit tests only!
105 * @throws MWException if called outside of PHPUnit tests.
107 * @param MediaWikiServices $services The new MediaWikiServices object.
109 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
111 public static function forceGlobalInstance( MediaWikiServices
$services ) {
112 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
113 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
116 $old = self
::getInstance();
117 self
::$instance = $services;
123 * Creates a new instance of MediaWikiServices and sets it as the global default
124 * instance. getInstance() will return a different MediaWikiServices object
125 * after every call to resetGlobalServiceLocator().
129 * @warning This should not be used during normal operation. It is intended for use
130 * when the configuration has changed significantly since bootstrap time, e.g.
131 * during the installation process or during testing.
133 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
134 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
135 * any of the services managed by MediaWikiServices exist. If any service objects
136 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
137 * with the operation of the services managed by the new MediaWikiServices.
138 * Operating with a mix of services created by the old and the new
139 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
140 * Any class implementing LAZY LOADING is especially prone to this problem,
141 * since instances would typically retain a reference to a storage layer service.
143 * @see forceGlobalInstance()
144 * @see resetGlobalInstance()
145 * @see resetBetweenTest()
147 * @param Config|null $bootstrapConfig The Config object to be registered as the
148 * 'BootstrapConfig' service. This has to contain at least the information
149 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
150 * config of the old instance of MediaWikiServices will be re-used. If there
151 * was no previous instance, a new GlobalVarConfig object will be used to
152 * bootstrap the services.
154 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
155 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
158 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
159 if ( self
::$instance === null ) {
160 // no global instance yet, nothing to reset
164 self
::failIfResetNotAllowed( __METHOD__
);
166 if ( $bootstrapConfig === null ) {
167 $bootstrapConfig = self
::$instance->getBootstrapConfig();
170 self
::$instance->destroy();
172 self
::$instance = self
::newInstance( $bootstrapConfig );
176 * Creates a new MediaWikiServices instance and initializes it according to the
177 * given $bootstrapConfig. In particular, all wiring files defined in the
178 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
180 * @param Config|null $bootstrapConfig The Config object to be registered as the
181 * 'BootstrapConfig' service. This has to contain at least the information
182 * needed to set up the 'ConfigFactory' service. If not provided, any call
183 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
184 * A MediaWikiServices instance without access to configuration is called
187 * @return MediaWikiServices
188 * @throws MWException
190 private static function newInstance( Config
$bootstrapConfig ) {
191 $instance = new self( $bootstrapConfig );
193 // Load the default wiring from the specified files.
194 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
195 $instance->loadWiringFiles( $wiringFiles );
197 // Provide a traditional hook point to allow extensions to configure services.
198 Hooks
::run( 'MediaWikiServices', [ $instance ] );
204 * Disables all storage layer services. After calling this, any attempt to access the
205 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
210 * @warning This is intended for extreme situations only and should never be used
211 * while serving normal web requests. Legitimate use cases for this method include
212 * the installation process. Test fixtures may also use this, if the fixture relies
215 * @see resetGlobalInstance()
216 * @see resetChildProcessServices()
218 public static function disableStorageBackend() {
219 // TODO: also disable some Caches, JobQueues, etc
220 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
221 $services = self
::getInstance();
223 foreach ( $destroy as $name ) {
224 $services->disableService( $name );
227 ObjectCache
::clear();
231 * Resets any services that may have become stale after a child process
232 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
233 * to call this method from the parent process.
237 * @note This is intended for use in the context of process forking only!
239 * @see resetGlobalInstance()
240 * @see disableStorageBackend()
242 public static function resetChildProcessServices() {
243 // NOTE: for now, just reset everything. Since we don't know the interdependencies
244 // between services, we can't do this more selectively at this time.
245 self
::resetGlobalInstance();
247 // Child, reseed because there is no bug in PHP:
248 // http://bugs.php.net/bug.php?id=42465
249 mt_srand( getmypid() );
253 * Resets the given service for testing purposes.
257 * @warning This is generally unsafe! Other services may still retain references
258 * to the stale service instance, leading to failures and inconsistencies. Subclasses
259 * may use this method to reset specific services under specific instances, but
260 * it should not be exposed to application logic.
262 * @note With proper dependency injection used throughout the codebase, this method
263 * should not be needed. It is provided to allow tests that pollute global service
264 * instances to clean up.
266 * @param string $name
267 * @param string $destroy Whether the service instance should be destroyed if it exists.
268 * When set to false, any existing service instance will effectively be detached
269 * from the container.
271 * @throws MWException if called outside of PHPUnit tests.
273 public function resetServiceForTesting( $name, $destroy = true ) {
274 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
275 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
278 $this->resetService( $name, $destroy );
282 * Convenience method that throws an exception unless it is called during a phase in which
283 * resetting of global services is allowed. In general, services should not be reset
284 * individually, since that may introduce inconsistencies.
288 * This method will throw an exception if:
290 * - self::$resetInProgress is false (to allow all services to be reset together
291 * via resetGlobalInstance)
292 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
293 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
295 * This method is intended to be used to safeguard against accidentally resetting
296 * global service instances that are not yet managed by MediaWikiServices. It is
297 * defined here in the MediaWikiServices services class to have a central place
298 * for managing service bootstrapping and resetting.
300 * @param string $method the name of the caller method, as given by __METHOD__.
302 * @throws MWException if called outside bootstrap mode.
304 * @see resetGlobalInstance()
305 * @see forceGlobalInstance()
306 * @see disableStorageBackend()
308 public static function failIfResetNotAllowed( $method ) {
309 if ( !defined( 'MW_PHPUNIT_TEST' )
310 && !defined( 'MW_PARSER_TEST' )
311 && !defined( 'MEDIAWIKI_INSTALL' )
312 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
313 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
315 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
320 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
321 * This has to contain at least the information needed to set up the 'ConfigFactory'
324 public function __construct( Config
$config ) {
325 parent
::__construct();
327 // Register the given Config object as the bootstrap config service.
328 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
333 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
336 * Returns the Config object containing the bootstrap configuration.
337 * Bootstrap configuration would typically include database credentials
338 * and other information that may be needed before the ConfigFactory
339 * service can be instantiated.
341 * @note This should only be used during bootstrapping, in particular
342 * when creating the MainConfig service. Application logic should
343 * use getMainConfig() to get a Config instances.
348 public function getBootstrapConfig() {
349 return $this->getService( 'BootstrapConfig' );
354 * @return ConfigFactory
356 public function getConfigFactory() {
357 return $this->getService( 'ConfigFactory' );
361 * Returns the Config object that provides configuration for MediaWiki core.
362 * This may or may not be the same object that is returned by getBootstrapConfig().
367 public function getMainConfig() {
368 return $this->getService( 'MainConfig' );
375 public function getSiteLookup() {
376 return $this->getService( 'SiteLookup' );
383 public function getSiteStore() {
384 return $this->getService( 'SiteStore' );
389 * @return StatsdDataFactory
391 public function getStatsdDataFactory() {
392 return $this->getService( 'StatsdDataFactory' );
397 * @return EventRelayerGroup
399 public function getEventRelayerGroup() {
400 return $this->getService( 'EventRelayerGroup' );
405 * @return SearchEngine
407 public function newSearchEngine() {
408 // New engine object every time, since they keep state
409 return $this->getService( 'SearchEngineFactory' )->create();
414 * @return SearchEngineFactory
416 public function getSearchEngineFactory() {
417 return $this->getService( 'SearchEngineFactory' );
422 * @return SearchEngineConfig
424 public function getSearchEngineConfig() {
425 return $this->getService( 'SearchEngineConfig' );
430 * @return SkinFactory
432 public function getSkinFactory() {
433 return $this->getService( 'SkinFactory' );
440 public function getDBLoadBalancerFactory() {
441 return $this->getService( 'DBLoadBalancerFactory' );
446 * @return LoadBalancer The main DB load balancer for the local wiki.
448 public function getDBLoadBalancer() {
449 return $this->getService( 'DBLoadBalancer' );
454 * @return WatchedItemStore
456 public function getWatchedItemStore() {
457 return $this->getService( 'WatchedItemStore' );
462 * @return GenderCache
464 public function getGenderCache() {
465 return $this->getService( 'GenderCache' );
472 public function getLinkCache() {
473 return $this->getService( 'LinkCache' );
478 * @return TitleFormatter
480 public function getTitleFormatter() {
481 return $this->getService( 'TitleFormatter' );
486 * @return TitleParser
488 public function getTitleParser() {
489 return $this->getService( 'TitleParser' );
492 ///////////////////////////////////////////////////////////////////////////
493 // NOTE: When adding a service getter here, don't forget to add a test
494 // case for it in MediaWikiServicesTest::provideGetters() and in
495 // MediaWikiServicesTest::provideGetService()!
496 ///////////////////////////////////////////////////////////////////////////