12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
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 );
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 resetGlobalServiceLocator().
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 resetGlobalServiceLocator() 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 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
154 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
157 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
158 if ( self
::$instance === null ) {
159 // no global instance yet, nothing to reset
163 self
::failIfResetNotAllowed( __METHOD__
);
165 if ( $bootstrapConfig === null ) {
166 $bootstrapConfig = self
::$instance->getBootstrapConfig();
169 self
::$instance->destroy();
171 self
::$instance = self
::newInstance( $bootstrapConfig );
175 * Creates a new MediaWikiServices instance and initializes it according to the
176 * given $bootstrapConfig. In particular, all wiring files defined in the
177 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
179 * @param Config|null $bootstrapConfig The Config object to be registered as the
180 * 'BootstrapConfig' service. This has to contain at least the information
181 * needed to set up the 'ConfigFactory' service. If not provided, any call
182 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
183 * A MediaWikiServices instance without access to configuration is called
186 * @return MediaWikiServices
187 * @throws MWException
189 private static function newInstance( Config
$bootstrapConfig ) {
190 $instance = new self( $bootstrapConfig );
192 // Load the default wiring from the specified files.
193 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
194 $instance->loadWiringFiles( $wiringFiles );
196 // Provide a traditional hook point to allow extensions to configure services.
197 Hooks
::run( 'MediaWikiServices', [ $instance ] );
203 * Disables all storage layer services. After calling this, any attempt to access the
204 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
209 * @warning This is intended for extreme situations only and should never be used
210 * while serving normal web requests. Legitimate use cases for this method include
211 * the installation process. Test fixtures may also use this, if the fixture relies
214 * @see resetGlobalInstance()
215 * @see resetChildProcessServices()
217 public static function disableStorageBackend() {
218 // TODO: also disable some Caches, JobQueues, etc
219 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
220 $services = self
::getInstance();
222 foreach ( $destroy as $name ) {
223 $services->disableService( $name );
228 * Resets any services that may have become stale after a child process
229 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
230 * to call this method from the parent process.
234 * @note This is intended for use in the context of process forking only!
236 * @see resetGlobalInstance()
237 * @see disableStorageBackend()
239 public static function resetChildProcessServices() {
240 // NOTE: for now, just reset everything. Since we don't know the interdependencies
241 // between services, we can't do this more selectively at this time.
242 self
::resetGlobalInstance();
244 // Child, reseed because there is no bug in PHP:
245 // http://bugs.php.net/bug.php?id=42465
246 mt_srand( getmypid() );
250 * Resets the given service for testing purposes.
254 * @warning This is generally unsafe! Other services may still retain references
255 * to the stale service instance, leading to failures and inconsistencies. Subclasses
256 * may use this method to reset specific services under specific instances, but
257 * it should not be exposed to application logic.
259 * @note With proper dependency injection used throughout the codebase, this method
260 * should not be needed. It is provided to allow tests that pollute global service
261 * instances to clean up.
263 * @param string $name
264 * @param string $destroy Whether the service instance should be destroyed if it exists.
265 * When set to false, any existing service instance will effectively be detached
266 * from the container.
268 * @throws MWException if called outside of PHPUnit tests.
270 public function resetServiceForTesting( $name, $destroy = true ) {
271 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
272 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
275 $this->resetService( $name, $destroy );
279 * Convenience method that throws an exception unless it is called during a phase in which
280 * resetting of global services is allowed. In general, services should not be reset
281 * individually, since that may introduce inconsistencies.
285 * This method will throw an exception if:
287 * - self::$resetInProgress is false (to allow all services to be reset together
288 * via resetGlobalInstance)
289 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
290 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
292 * This method is intended to be used to safeguard against accidentally resetting
293 * global service instances that are not yet managed by MediaWikiServices. It is
294 * defined here in the MediaWikiServices services class to have a central place
295 * for managing service bootstrapping and resetting.
297 * @param string $method the name of the caller method, as given by __METHOD__.
299 * @throws MWException if called outside bootstrap mode.
301 * @see resetGlobalInstance()
302 * @see forceGlobalInstance()
303 * @see disableStorageBackend()
305 public static function failIfResetNotAllowed( $method ) {
306 if ( !defined( 'MW_PHPUNIT_TEST' )
307 && !defined( 'MW_PARSER_TEST' )
308 && !defined( 'MEDIAWIKI_INSTALL' )
309 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
310 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
312 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
317 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
318 * This has to contain at least the information needed to set up the 'ConfigFactory'
321 public function __construct( Config
$config ) {
322 parent
::__construct();
324 // Register the given Config object as the bootstrap config service.
325 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
330 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
333 * Returns the Config object containing the bootstrap configuration.
334 * Bootstrap configuration would typically include database credentials
335 * and other information that may be needed before the ConfigFactory
336 * service can be instantiated.
338 * @note This should only be used during bootstrapping, in particular
339 * when creating the MainConfig service. Application logic should
340 * use getMainConfig() to get a Config instances.
345 public function getBootstrapConfig() {
346 return $this->getService( 'BootstrapConfig' );
351 * @return ConfigFactory
353 public function getConfigFactory() {
354 return $this->getService( 'ConfigFactory' );
358 * Returns the Config object that provides configuration for MediaWiki core.
359 * This may or may not be the same object that is returned by getBootstrapConfig().
364 public function getMainConfig() {
365 return $this->getService( 'MainConfig' );
372 public function getSiteLookup() {
373 return $this->getService( 'SiteLookup' );
380 public function getSiteStore() {
381 return $this->getService( 'SiteStore' );
386 * @return StatsdDataFactory
388 public function getStatsdDataFactory() {
389 return $this->getService( 'StatsdDataFactory' );
394 * @return EventRelayerGroup
396 public function getEventRelayerGroup() {
397 return $this->getService( 'EventRelayerGroup' );
402 * @return SearchEngine
404 public function newSearchEngine() {
405 // New engine object every time, since they keep state
406 return $this->getService( 'SearchEngineFactory' )->create();
411 * @return SearchEngineFactory
413 public function getSearchEngineFactory() {
414 return $this->getService( 'SearchEngineFactory' );
419 * @return SearchEngineConfig
421 public function getSearchEngineConfig() {
422 return $this->getService( 'SearchEngineConfig' );
427 * @return SkinFactory
429 public function getSkinFactory() {
430 return $this->getService( 'SkinFactory' );
437 public function getDBLoadBalancerFactory() {
438 return $this->getService( 'DBLoadBalancerFactory' );
443 * @return LoadBalancer The main DB load balancer for the local wiki.
445 public function getDBLoadBalancer() {
446 return $this->getService( 'DBLoadBalancer' );
451 * @return WatchedItemStore
453 public function getWatchedItemStore() {
454 return $this->getService( 'WatchedItemStore' );
459 * @return GenderCache
461 public function getGenderCache() {
462 return $this->getService( 'GenderCache' );
469 public function getLinkCache() {
470 return $this->getService( 'LinkCache' );
475 * @return TitleFormatter
477 public function getTitleFormatter() {
478 return $this->getService( 'TitleFormatter' );
483 * @return TitleParser
485 public function getTitleParser() {
486 return $this->getService( 'TitleParser' );
489 ///////////////////////////////////////////////////////////////////////////
490 // NOTE: When adding a service getter here, don't forget to add a test
491 // case for it in MediaWikiServicesTest::provideGetters() and in
492 // MediaWikiServicesTest::provideGetService()!
493 ///////////////////////////////////////////////////////////////////////////