10 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
12 use MediaWiki\Services\ServiceContainer
;
16 use SearchEngineConfig
;
17 use SearchEngineFactory
;
24 * Service locator for MediaWiki core services.
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 2 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License along
37 * with this program; if not, write to the Free Software Foundation, Inc.,
38 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
39 * http://www.gnu.org/copyleft/gpl.html
47 * MediaWikiServices is the service locator for the application scope of MediaWiki.
48 * Its implemented as a simple configurable DI container.
49 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
50 * the network of service objects that defines MediaWiki's application logic.
51 * It acts as an entry point to MediaWiki's dependency injection mechanism.
53 * Services are defined in the "wiring" array passed to the constructor,
54 * or by calling defineService().
56 * @see docs/injection.txt for an overview of using dependency injection in the
57 * MediaWiki code base.
59 class MediaWikiServices
extends ServiceContainer
{
62 * @var MediaWikiServices|null
64 private static $instance = null;
67 * Returns the global default instance of the top level service locator.
69 * The default instance is initialized using the service instantiator functions
70 * defined in ServiceWiring.php.
72 * @note This should only be called by static functions! The instance returned here
73 * should not be passed around! Objects that need access to a service should have
74 * that service injected into the constructor, never a service locator!
76 * @return MediaWikiServices
78 public static function getInstance() {
79 if ( self
::$instance === null ) {
80 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
81 // but some information from the global scope has to be injected here,
82 // even if it's just a file name or database credentials to load
83 // configuration from.
84 $bootstrapConfig = new GlobalVarConfig();
85 self
::$instance = self
::newInstance( $bootstrapConfig );
88 return self
::$instance;
92 * Replaces the global MediaWikiServices instance.
94 * @note This is for use in PHPUnit tests only!
96 * @throws MWException if called outside of PHPUnit tests.
98 * @param MediaWikiServices $services The new MediaWikiServices object.
100 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
102 public static function forceGlobalInstance( MediaWikiServices
$services ) {
103 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
104 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
107 $old = self
::getInstance();
108 self
::$instance = $services;
114 * Creates a new instance of MediaWikiServices and sets it as the global default
115 * instance. getInstance() will return a different MediaWikiServices object
116 * after every call to resetGlobalServiceLocator().
118 * @warning This should not be used during normal operation. It is intended for use
119 * when the configuration has changed significantly since bootstrap time, e.g.
120 * during the installation process or during testing.
122 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
123 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
124 * any of the services managed by MediaWikiServices exist. If any service objects
125 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
126 * with the operation of the services managed by the new MediaWikiServices.
127 * Operating with a mix of services created by the old and the new
128 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
129 * Any class implementing LAZY LOADING is especially prone to this problem,
130 * since instances would typically retain a reference to a storage layer service.
132 * @see forceGlobalInstance()
133 * @see resetGlobalInstance()
134 * @see resetBetweenTest()
136 * @param Config|null $bootstrapConfig The Config object to be registered as the
137 * 'BootstrapConfig' service. This has to contain at least the information
138 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
139 * config of the old instance of MediaWikiServices will be re-used. If there
140 * was no previous instance, a new GlobalVarConfig object will be used to
141 * bootstrap the services.
143 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
144 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
147 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
148 if ( self
::$instance === null ) {
149 // no global instance yet, nothing to reset
153 self
::failIfResetNotAllowed( __METHOD__
);
155 if ( $bootstrapConfig === null ) {
156 $bootstrapConfig = self
::$instance->getBootstrapConfig();
159 self
::$instance->destroy();
161 self
::$instance = self
::newInstance( $bootstrapConfig );
165 * Creates a new MediaWikiServices instance and initializes it according to the
166 * given $bootstrapConfig. In particular, all wiring files defined in the
167 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
169 * @param Config|null $bootstrapConfig The Config object to be registered as the
170 * 'BootstrapConfig' service. This has to contain at least the information
171 * needed to set up the 'ConfigFactory' service. If not provided, any call
172 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
173 * A MediaWikiServices instance without access to configuration is called
176 * @return MediaWikiServices
177 * @throws MWException
179 private static function newInstance( Config
$bootstrapConfig ) {
180 $instance = new self( $bootstrapConfig );
182 // Load the default wiring from the specified files.
183 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
184 $instance->loadWiringFiles( $wiringFiles );
186 // Provide a traditional hook point to allow extensions to configure services.
187 Hooks
::run( 'MediaWikiServices', [ $instance ] );
193 * Disables all storage layer services. After calling this, any attempt to access the
194 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
197 * @warning This is intended for extreme situations only and should never be used
198 * while serving normal web requests. Legitimate use cases for this method include
199 * the installation process. Test fixtures may also use this, if the fixture relies
202 * @see resetGlobalInstance()
203 * @see resetChildProcessServices()
205 public static function disableStorageBackend() {
206 // TODO: also disable some Caches, JobQueues, etc
207 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
208 $services = self
::getInstance();
210 foreach ( $destroy as $name ) {
211 $services->disableService( $name );
216 * Resets any services that may have become stale after a child process
217 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
218 * to call this method from the parent process.
220 * @note This is intended for use in the context of process forking only!
222 * @see resetGlobalInstance()
223 * @see disableStorageBackend()
225 public static function resetChildProcessServices() {
226 // NOTE: for now, just reset everything. Since we don't know the interdependencies
227 // between services, we can't do this more selectively at this time.
228 self
::resetGlobalInstance();
230 // Child, reseed because there is no bug in PHP:
231 // http://bugs.php.net/bug.php?id=42465
232 mt_srand( getmypid() );
236 * Resets the given service for testing purposes.
238 * @warning This is generally unsafe! Other services may still retain references
239 * to the stale service instance, leading to failures and inconsistencies. Subclasses
240 * may use this method to reset specific services under specific instances, but
241 * it should not be exposed to application logic.
243 * @note With proper dependency injection used throughout the codebase, this method
244 * should not be needed. It is provided to allow tests that pollute global service
245 * instances to clean up.
247 * @param string $name
248 * @param string $destroy Whether the service instance should be destroyed if it exists.
249 * When set to false, any existing service instance will effectively be detached
250 * from the container.
252 * @throws MWException if called outside of PHPUnit tests.
254 public function resetServiceForTesting( $name, $destroy = true ) {
255 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
256 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
259 $this->resetService( $name, $destroy );
263 * Convenience method that throws an exception unless it is called during a phase in which
264 * resetting of global services is allowed. In general, services should not be reset
265 * individually, since that may introduce inconsistencies.
267 * This method will throw an exception if:
269 * - self::$resetInProgress is false (to allow all services to be reset together
270 * via resetGlobalInstance)
271 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
272 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
274 * This method is intended to be used to safeguard against accidentally resetting
275 * global service instances that are not yet managed by MediaWikiServices. It is
276 * defined here in the MediaWikiServices services class to have a central place
277 * for managing service bootstrapping and resetting.
279 * @param string $method the name of the caller method, as given by __METHOD__.
281 * @throws MWException if called outside bootstrap mode.
283 * @see resetGlobalInstance()
284 * @see forceGlobalInstance()
285 * @see disableStorageBackend()
287 public static function failIfResetNotAllowed( $method ) {
288 if ( !defined( 'MW_PHPUNIT_TEST' )
289 && !defined( 'MW_PARSER_TEST' )
290 && !defined( 'MEDIAWIKI_INSTALL' )
291 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
292 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
294 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
299 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
300 * This has to contain at least the information needed to set up the 'ConfigFactory'
303 public function __construct( Config
$config ) {
304 parent
::__construct();
306 // Register the given Config object as the bootstrap config service.
307 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
312 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
315 * Returns the Config object containing the bootstrap configuration.
316 * Bootstrap configuration would typically include database credentials
317 * and other information that may be needed before the ConfigFactory
318 * service can be instantiated.
320 * @note This should only be used during bootstrapping, in particular
321 * when creating the MainConfig service. Application logic should
322 * use getMainConfig() to get a Config instances.
326 public function getBootstrapConfig() {
327 return $this->getService( 'BootstrapConfig' );
331 * @return ConfigFactory
333 public function getConfigFactory() {
334 return $this->getService( 'ConfigFactory' );
338 * Returns the Config object that provides configuration for MediaWiki core.
339 * This may or may not be the same object that is returned by getBootstrapConfig().
343 public function getMainConfig() {
344 return $this->getService( 'MainConfig' );
350 public function getSiteLookup() {
351 return $this->getService( 'SiteLookup' );
357 public function getSiteStore() {
358 return $this->getService( 'SiteStore' );
362 * @return StatsdDataFactory
364 public function getStatsdDataFactory() {
365 return $this->getService( 'StatsdDataFactory' );
369 * @return EventRelayerGroup
371 public function getEventRelayerGroup() {
372 return $this->getService( 'EventRelayerGroup' );
376 * @return SearchEngine
378 public function newSearchEngine() {
379 // New engine object every time, since they keep state
380 return $this->getService( 'SearchEngineFactory' )->create();
384 * @return SearchEngineFactory
386 public function getSearchEngineFactory() {
387 return $this->getService( 'SearchEngineFactory' );
391 * @return SearchEngineConfig
393 public function getSearchEngineConfig() {
394 return $this->getService( 'SearchEngineConfig' );
398 * @return SkinFactory
400 public function getSkinFactory() {
401 return $this->getService( 'SkinFactory' );
407 public function getDBLoadBalancerFactory() {
408 return $this->getService( 'DBLoadBalancerFactory' );
412 * @return LoadBalancer The main DB load balancer for the local wiki.
414 public function getDBLoadBalancer() {
415 return $this->getService( 'DBLoadBalancer' );
419 * @return WatchedItemStore
421 public function getWatchedItemStore() {
422 return $this->getService( 'WatchedItemStore' );
425 ///////////////////////////////////////////////////////////////////////////
426 // NOTE: When adding a service getter here, don't forget to add a test
427 // case for it in MediaWikiServicesTest::provideGetters() and in
428 // MediaWikiServicesTest::provideGetService()!
429 ///////////////////////////////////////////////////////////////////////////