12 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
14 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 );
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 resetGlobalServiceLocator().
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 resetGlobalServiceLocator() 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 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
156 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
159 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
160 if ( self
::$instance === null ) {
161 // no global instance yet, nothing to reset
165 self
::failIfResetNotAllowed( __METHOD__
);
167 if ( $bootstrapConfig === null ) {
168 $bootstrapConfig = self
::$instance->getBootstrapConfig();
171 self
::$instance->destroy();
173 self
::$instance = self
::newInstance( $bootstrapConfig );
177 * Creates a new MediaWikiServices instance and initializes it according to the
178 * given $bootstrapConfig. In particular, all wiring files defined in the
179 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
181 * @param Config|null $bootstrapConfig The Config object to be registered as the
182 * 'BootstrapConfig' service. This has to contain at least the information
183 * needed to set up the 'ConfigFactory' service. If not provided, any call
184 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
185 * A MediaWikiServices instance without access to configuration is called
188 * @return MediaWikiServices
189 * @throws MWException
191 private static function newInstance( Config
$bootstrapConfig ) {
192 $instance = new self( $bootstrapConfig );
194 // Load the default wiring from the specified files.
195 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
196 $instance->loadWiringFiles( $wiringFiles );
198 // Provide a traditional hook point to allow extensions to configure services.
199 Hooks
::run( 'MediaWikiServices', [ $instance ] );
205 * Disables all storage layer services. After calling this, any attempt to access the
206 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
211 * @warning This is intended for extreme situations only and should never be used
212 * while serving normal web requests. Legitimate use cases for this method include
213 * the installation process. Test fixtures may also use this, if the fixture relies
216 * @see resetGlobalInstance()
217 * @see resetChildProcessServices()
219 public static function disableStorageBackend() {
220 // TODO: also disable some Caches, JobQueues, etc
221 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
222 $services = self
::getInstance();
224 foreach ( $destroy as $name ) {
225 $services->disableService( $name );
228 ObjectCache
::clear();
232 * Resets any services that may have become stale after a child process
233 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
234 * to call this method from the parent process.
238 * @note This is intended for use in the context of process forking only!
240 * @see resetGlobalInstance()
241 * @see disableStorageBackend()
243 public static function resetChildProcessServices() {
244 // NOTE: for now, just reset everything. Since we don't know the interdependencies
245 // between services, we can't do this more selectively at this time.
246 self
::resetGlobalInstance();
248 // Child, reseed because there is no bug in PHP:
249 // http://bugs.php.net/bug.php?id=42465
250 mt_srand( getmypid() );
254 * Resets the given service for testing purposes.
258 * @warning This is generally unsafe! Other services may still retain references
259 * to the stale service instance, leading to failures and inconsistencies. Subclasses
260 * may use this method to reset specific services under specific instances, but
261 * it should not be exposed to application logic.
263 * @note With proper dependency injection used throughout the codebase, this method
264 * should not be needed. It is provided to allow tests that pollute global service
265 * instances to clean up.
267 * @param string $name
268 * @param string $destroy Whether the service instance should be destroyed if it exists.
269 * When set to false, any existing service instance will effectively be detached
270 * from the container.
272 * @throws MWException if called outside of PHPUnit tests.
274 public function resetServiceForTesting( $name, $destroy = true ) {
275 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
276 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
279 $this->resetService( $name, $destroy );
283 * Convenience method that throws an exception unless it is called during a phase in which
284 * resetting of global services is allowed. In general, services should not be reset
285 * individually, since that may introduce inconsistencies.
289 * This method will throw an exception if:
291 * - self::$resetInProgress is false (to allow all services to be reset together
292 * via resetGlobalInstance)
293 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
294 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
296 * This method is intended to be used to safeguard against accidentally resetting
297 * global service instances that are not yet managed by MediaWikiServices. It is
298 * defined here in the MediaWikiServices services class to have a central place
299 * for managing service bootstrapping and resetting.
301 * @param string $method the name of the caller method, as given by __METHOD__.
303 * @throws MWException if called outside bootstrap mode.
305 * @see resetGlobalInstance()
306 * @see forceGlobalInstance()
307 * @see disableStorageBackend()
309 public static function failIfResetNotAllowed( $method ) {
310 if ( !defined( 'MW_PHPUNIT_TEST' )
311 && !defined( 'MW_PARSER_TEST' )
312 && !defined( 'MEDIAWIKI_INSTALL' )
313 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
314 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
316 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
321 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
322 * This has to contain at least the information needed to set up the 'ConfigFactory'
325 public function __construct( Config
$config ) {
326 parent
::__construct();
328 // Register the given Config object as the bootstrap config service.
329 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
334 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
337 * Returns the Config object containing the bootstrap configuration.
338 * Bootstrap configuration would typically include database credentials
339 * and other information that may be needed before the ConfigFactory
340 * service can be instantiated.
342 * @note This should only be used during bootstrapping, in particular
343 * when creating the MainConfig service. Application logic should
344 * use getMainConfig() to get a Config instances.
349 public function getBootstrapConfig() {
350 return $this->getService( 'BootstrapConfig' );
355 * @return ConfigFactory
357 public function getConfigFactory() {
358 return $this->getService( 'ConfigFactory' );
362 * Returns the Config object that provides configuration for MediaWiki core.
363 * This may or may not be the same object that is returned by getBootstrapConfig().
368 public function getMainConfig() {
369 return $this->getService( 'MainConfig' );
376 public function getSiteLookup() {
377 return $this->getService( 'SiteLookup' );
384 public function getSiteStore() {
385 return $this->getService( 'SiteStore' );
390 * @return InterwikiLookup
392 public function getInterwikiLookup() {
393 return $this->getService( 'InterwikiLookup' );
398 * @return StatsdDataFactory
400 public function getStatsdDataFactory() {
401 return $this->getService( 'StatsdDataFactory' );
406 * @return EventRelayerGroup
408 public function getEventRelayerGroup() {
409 return $this->getService( 'EventRelayerGroup' );
414 * @return SearchEngine
416 public function newSearchEngine() {
417 // New engine object every time, since they keep state
418 return $this->getService( 'SearchEngineFactory' )->create();
423 * @return SearchEngineFactory
425 public function getSearchEngineFactory() {
426 return $this->getService( 'SearchEngineFactory' );
431 * @return SearchEngineConfig
433 public function getSearchEngineConfig() {
434 return $this->getService( 'SearchEngineConfig' );
439 * @return SkinFactory
441 public function getSkinFactory() {
442 return $this->getService( 'SkinFactory' );
449 public function getDBLoadBalancerFactory() {
450 return $this->getService( 'DBLoadBalancerFactory' );
455 * @return LoadBalancer The main DB load balancer for the local wiki.
457 public function getDBLoadBalancer() {
458 return $this->getService( 'DBLoadBalancer' );
463 * @return WatchedItemStore
465 public function getWatchedItemStore() {
466 return $this->getService( 'WatchedItemStore' );
471 * @return GenderCache
473 public function getGenderCache() {
474 return $this->getService( 'GenderCache' );
481 public function getLinkCache() {
482 return $this->getService( 'LinkCache' );
487 * @return TitleFormatter
489 public function getTitleFormatter() {
490 return $this->getService( 'TitleFormatter' );
495 * @return TitleParser
497 public function getTitleParser() {
498 return $this->getService( 'TitleParser' );
501 ///////////////////////////////////////////////////////////////////////////
502 // NOTE: When adding a service getter here, don't forget to add a test
503 // case for it in MediaWikiServicesTest::provideGetters() and in
504 // MediaWikiServicesTest::provideGetService()!
505 ///////////////////////////////////////////////////////////////////////////