11 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
13 use MediaWiki\Services\ServiceContainer
;
17 use SearchEngineConfig
;
18 use SearchEngineFactory
;
25 * Service locator for MediaWiki core services.
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 2 of the License, or
30 * (at your option) any later version.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public License along
38 * with this program; if not, write to the Free Software Foundation, Inc.,
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
40 * http://www.gnu.org/copyleft/gpl.html
48 * MediaWikiServices is the service locator for the application scope of MediaWiki.
49 * Its implemented as a simple configurable DI container.
50 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
51 * the network of service objects that defines MediaWiki's application logic.
52 * It acts as an entry point to MediaWiki's dependency injection mechanism.
54 * Services are defined in the "wiring" array passed to the constructor,
55 * or by calling defineService().
57 * @see docs/injection.txt for an overview of using dependency injection in the
58 * MediaWiki code base.
60 class MediaWikiServices
extends ServiceContainer
{
63 * @var MediaWikiServices|null
65 private static $instance = null;
68 * Returns the global default instance of the top level service locator.
72 * The default instance is initialized using the service instantiator functions
73 * defined in ServiceWiring.php.
75 * @note This should only be called by static functions! The instance returned here
76 * should not be passed around! Objects that need access to a service should have
77 * that service injected into the constructor, never a service locator!
79 * @return MediaWikiServices
81 public static function getInstance() {
82 if ( self
::$instance === null ) {
83 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
84 // but some information from the global scope has to be injected here,
85 // even if it's just a file name or database credentials to load
86 // configuration from.
87 $bootstrapConfig = new GlobalVarConfig();
88 self
::$instance = self
::newInstance( $bootstrapConfig );
91 return self
::$instance;
95 * Replaces the global MediaWikiServices instance.
99 * @note This is for use in PHPUnit tests only!
101 * @throws MWException if called outside of PHPUnit tests.
103 * @param MediaWikiServices $services The new MediaWikiServices object.
105 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
107 public static function forceGlobalInstance( MediaWikiServices
$services ) {
108 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
109 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
112 $old = self
::getInstance();
113 self
::$instance = $services;
119 * Creates a new instance of MediaWikiServices and sets it as the global default
120 * instance. getInstance() will return a different MediaWikiServices object
121 * after every call to resetGlobalServiceLocator().
125 * @warning This should not be used during normal operation. It is intended for use
126 * when the configuration has changed significantly since bootstrap time, e.g.
127 * during the installation process or during testing.
129 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
130 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
131 * any of the services managed by MediaWikiServices exist. If any service objects
132 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
133 * with the operation of the services managed by the new MediaWikiServices.
134 * Operating with a mix of services created by the old and the new
135 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
136 * Any class implementing LAZY LOADING is especially prone to this problem,
137 * since instances would typically retain a reference to a storage layer service.
139 * @see forceGlobalInstance()
140 * @see resetGlobalInstance()
141 * @see resetBetweenTest()
143 * @param Config|null $bootstrapConfig The Config object to be registered as the
144 * 'BootstrapConfig' service. This has to contain at least the information
145 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
146 * config of the old instance of MediaWikiServices will be re-used. If there
147 * was no previous instance, a new GlobalVarConfig object will be used to
148 * bootstrap the services.
150 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
151 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
154 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
155 if ( self
::$instance === null ) {
156 // no global instance yet, nothing to reset
160 self
::failIfResetNotAllowed( __METHOD__
);
162 if ( $bootstrapConfig === null ) {
163 $bootstrapConfig = self
::$instance->getBootstrapConfig();
166 self
::$instance->destroy();
168 self
::$instance = self
::newInstance( $bootstrapConfig );
172 * Creates a new MediaWikiServices instance and initializes it according to the
173 * given $bootstrapConfig. In particular, all wiring files defined in the
174 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
176 * @param Config|null $bootstrapConfig The Config object to be registered as the
177 * 'BootstrapConfig' service. This has to contain at least the information
178 * needed to set up the 'ConfigFactory' service. If not provided, any call
179 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
180 * A MediaWikiServices instance without access to configuration is called
183 * @return MediaWikiServices
184 * @throws MWException
186 private static function newInstance( Config
$bootstrapConfig ) {
187 $instance = new self( $bootstrapConfig );
189 // Load the default wiring from the specified files.
190 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
191 $instance->loadWiringFiles( $wiringFiles );
193 // Provide a traditional hook point to allow extensions to configure services.
194 Hooks
::run( 'MediaWikiServices', [ $instance ] );
200 * Disables all storage layer services. After calling this, any attempt to access the
201 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
206 * @warning This is intended for extreme situations only and should never be used
207 * while serving normal web requests. Legitimate use cases for this method include
208 * the installation process. Test fixtures may also use this, if the fixture relies
211 * @see resetGlobalInstance()
212 * @see resetChildProcessServices()
214 public static function disableStorageBackend() {
215 // TODO: also disable some Caches, JobQueues, etc
216 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
217 $services = self
::getInstance();
219 foreach ( $destroy as $name ) {
220 $services->disableService( $name );
225 * Resets any services that may have become stale after a child process
226 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
227 * to call this method from the parent process.
231 * @note This is intended for use in the context of process forking only!
233 * @see resetGlobalInstance()
234 * @see disableStorageBackend()
236 public static function resetChildProcessServices() {
237 // NOTE: for now, just reset everything. Since we don't know the interdependencies
238 // between services, we can't do this more selectively at this time.
239 self
::resetGlobalInstance();
241 // Child, reseed because there is no bug in PHP:
242 // http://bugs.php.net/bug.php?id=42465
243 mt_srand( getmypid() );
247 * Resets the given service for testing purposes.
251 * @warning This is generally unsafe! Other services may still retain references
252 * to the stale service instance, leading to failures and inconsistencies. Subclasses
253 * may use this method to reset specific services under specific instances, but
254 * it should not be exposed to application logic.
256 * @note With proper dependency injection used throughout the codebase, this method
257 * should not be needed. It is provided to allow tests that pollute global service
258 * instances to clean up.
260 * @param string $name
261 * @param string $destroy Whether the service instance should be destroyed if it exists.
262 * When set to false, any existing service instance will effectively be detached
263 * from the container.
265 * @throws MWException if called outside of PHPUnit tests.
267 public function resetServiceForTesting( $name, $destroy = true ) {
268 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
269 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
272 $this->resetService( $name, $destroy );
276 * Convenience method that throws an exception unless it is called during a phase in which
277 * resetting of global services is allowed. In general, services should not be reset
278 * individually, since that may introduce inconsistencies.
282 * This method will throw an exception if:
284 * - self::$resetInProgress is false (to allow all services to be reset together
285 * via resetGlobalInstance)
286 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
287 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
289 * This method is intended to be used to safeguard against accidentally resetting
290 * global service instances that are not yet managed by MediaWikiServices. It is
291 * defined here in the MediaWikiServices services class to have a central place
292 * for managing service bootstrapping and resetting.
294 * @param string $method the name of the caller method, as given by __METHOD__.
296 * @throws MWException if called outside bootstrap mode.
298 * @see resetGlobalInstance()
299 * @see forceGlobalInstance()
300 * @see disableStorageBackend()
302 public static function failIfResetNotAllowed( $method ) {
303 if ( !defined( 'MW_PHPUNIT_TEST' )
304 && !defined( 'MW_PARSER_TEST' )
305 && !defined( 'MEDIAWIKI_INSTALL' )
306 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
307 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
309 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
314 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
315 * This has to contain at least the information needed to set up the 'ConfigFactory'
318 public function __construct( Config
$config ) {
319 parent
::__construct();
321 // Register the given Config object as the bootstrap config service.
322 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
327 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
330 * Returns the Config object containing the bootstrap configuration.
331 * Bootstrap configuration would typically include database credentials
332 * and other information that may be needed before the ConfigFactory
333 * service can be instantiated.
335 * @note This should only be used during bootstrapping, in particular
336 * when creating the MainConfig service. Application logic should
337 * use getMainConfig() to get a Config instances.
342 public function getBootstrapConfig() {
343 return $this->getService( 'BootstrapConfig' );
348 * @return ConfigFactory
350 public function getConfigFactory() {
351 return $this->getService( 'ConfigFactory' );
355 * Returns the Config object that provides configuration for MediaWiki core.
356 * This may or may not be the same object that is returned by getBootstrapConfig().
361 public function getMainConfig() {
362 return $this->getService( 'MainConfig' );
369 public function getSiteLookup() {
370 return $this->getService( 'SiteLookup' );
377 public function getSiteStore() {
378 return $this->getService( 'SiteStore' );
383 * @return StatsdDataFactory
385 public function getStatsdDataFactory() {
386 return $this->getService( 'StatsdDataFactory' );
391 * @return EventRelayerGroup
393 public function getEventRelayerGroup() {
394 return $this->getService( 'EventRelayerGroup' );
399 * @return SearchEngine
401 public function newSearchEngine() {
402 // New engine object every time, since they keep state
403 return $this->getService( 'SearchEngineFactory' )->create();
408 * @return SearchEngineFactory
410 public function getSearchEngineFactory() {
411 return $this->getService( 'SearchEngineFactory' );
416 * @return SearchEngineConfig
418 public function getSearchEngineConfig() {
419 return $this->getService( 'SearchEngineConfig' );
424 * @return SkinFactory
426 public function getSkinFactory() {
427 return $this->getService( 'SkinFactory' );
434 public function getDBLoadBalancerFactory() {
435 return $this->getService( 'DBLoadBalancerFactory' );
440 * @return LoadBalancer The main DB load balancer for the local wiki.
442 public function getDBLoadBalancer() {
443 return $this->getService( 'DBLoadBalancer' );
448 * @return WatchedItemStore
450 public function getWatchedItemStore() {
451 return $this->getService( 'WatchedItemStore' );
456 * @return GenderCache
458 public function getGenderCache() {
459 return $this->getService( 'GenderCache' );
462 ///////////////////////////////////////////////////////////////////////////
463 // NOTE: When adding a service getter here, don't forget to add a test
464 // case for it in MediaWikiServicesTest::provideGetters() and in
465 // MediaWikiServicesTest::provideGetService()!
466 ///////////////////////////////////////////////////////////////////////////