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.
70 * The default instance is initialized using the service instantiator functions
71 * defined in ServiceWiring.php.
73 * @note This should only be called by static functions! The instance returned here
74 * should not be passed around! Objects that need access to a service should have
75 * that service injected into the constructor, never a service locator!
77 * @return MediaWikiServices
79 public static function getInstance() {
80 if ( self
::$instance === null ) {
81 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
82 // but some information from the global scope has to be injected here,
83 // even if it's just a file name or database credentials to load
84 // configuration from.
85 $bootstrapConfig = new GlobalVarConfig();
86 self
::$instance = self
::newInstance( $bootstrapConfig );
89 return self
::$instance;
93 * Replaces the global MediaWikiServices instance.
95 * @note This is for use in PHPUnit tests only!
97 * @throws MWException if called outside of PHPUnit tests.
99 * @param MediaWikiServices $services The new MediaWikiServices object.
101 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
103 public static function forceGlobalInstance( MediaWikiServices
$services ) {
104 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
105 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
108 $old = self
::getInstance();
109 self
::$instance = $services;
115 * Creates a new instance of MediaWikiServices and sets it as the global default
116 * instance. getInstance() will return a different MediaWikiServices object
117 * after every call to resetGlobalServiceLocator().
119 * @warning This should not be used during normal operation. It is intended for use
120 * when the configuration has changed significantly since bootstrap time, e.g.
121 * during the installation process or during testing.
123 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
124 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
125 * any of the services managed by MediaWikiServices exist. If any service objects
126 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
127 * with the operation of the services managed by the new MediaWikiServices.
128 * Operating with a mix of services created by the old and the new
129 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
130 * Any class implementing LAZY LOADING is especially prone to this problem,
131 * since instances would typically retain a reference to a storage layer service.
133 * @see forceGlobalInstance()
134 * @see resetGlobalInstance()
135 * @see resetBetweenTest()
137 * @param Config|null $bootstrapConfig The Config object to be registered as the
138 * 'BootstrapConfig' service. This has to contain at least the information
139 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
140 * config of the old instance of MediaWikiServices will be re-used. If there
141 * was no previous instance, a new GlobalVarConfig object will be used to
142 * bootstrap the services.
144 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
145 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
148 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
149 if ( self
::$instance === null ) {
150 // no global instance yet, nothing to reset
154 self
::failIfResetNotAllowed( __METHOD__
);
156 if ( $bootstrapConfig === null ) {
157 $bootstrapConfig = self
::$instance->getBootstrapConfig();
160 self
::$instance->destroy();
162 self
::$instance = self
::newInstance( $bootstrapConfig );
166 * Creates a new MediaWikiServices instance and initializes it according to the
167 * given $bootstrapConfig. In particular, all wiring files defined in the
168 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
170 * @param Config|null $bootstrapConfig The Config object to be registered as the
171 * 'BootstrapConfig' service. This has to contain at least the information
172 * needed to set up the 'ConfigFactory' service. If not provided, any call
173 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
174 * A MediaWikiServices instance without access to configuration is called
177 * @return MediaWikiServices
178 * @throws MWException
180 private static function newInstance( Config
$bootstrapConfig ) {
181 $instance = new self( $bootstrapConfig );
183 // Load the default wiring from the specified files.
184 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
185 $instance->loadWiringFiles( $wiringFiles );
187 // Provide a traditional hook point to allow extensions to configure services.
188 Hooks
::run( 'MediaWikiServices', [ $instance ] );
194 * Disables all storage layer services. After calling this, any attempt to access the
195 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
198 * @warning This is intended for extreme situations only and should never be used
199 * while serving normal web requests. Legitimate use cases for this method include
200 * the installation process. Test fixtures may also use this, if the fixture relies
203 * @see resetGlobalInstance()
204 * @see resetChildProcessServices()
206 public static function disableStorageBackend() {
207 // TODO: also disable some Caches, JobQueues, etc
208 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
209 $services = self
::getInstance();
211 foreach ( $destroy as $name ) {
212 $services->disableService( $name );
217 * Resets any services that may have become stale after a child process
218 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
219 * to call this method from the parent process.
221 * @note This is intended for use in the context of process forking only!
223 * @see resetGlobalInstance()
224 * @see disableStorageBackend()
226 public static function resetChildProcessServices() {
227 // NOTE: for now, just reset everything. Since we don't know the interdependencies
228 // between services, we can't do this more selectively at this time.
229 self
::resetGlobalInstance();
231 // Child, reseed because there is no bug in PHP:
232 // http://bugs.php.net/bug.php?id=42465
233 mt_srand( getmypid() );
237 * Resets the given service for testing purposes.
239 * @warning This is generally unsafe! Other services may still retain references
240 * to the stale service instance, leading to failures and inconsistencies. Subclasses
241 * may use this method to reset specific services under specific instances, but
242 * it should not be exposed to application logic.
244 * @note With proper dependency injection used throughout the codebase, this method
245 * should not be needed. It is provided to allow tests that pollute global service
246 * instances to clean up.
248 * @param string $name
249 * @param string $destroy Whether the service instance should be destroyed if it exists.
250 * When set to false, any existing service instance will effectively be detached
251 * from the container.
253 * @throws MWException if called outside of PHPUnit tests.
255 public function resetServiceForTesting( $name, $destroy = true ) {
256 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
257 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
260 $this->resetService( $name, $destroy );
264 * Convenience method that throws an exception unless it is called during a phase in which
265 * resetting of global services is allowed. In general, services should not be reset
266 * individually, since that may introduce inconsistencies.
268 * This method will throw an exception if:
270 * - self::$resetInProgress is false (to allow all services to be reset together
271 * via resetGlobalInstance)
272 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
273 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
275 * This method is intended to be used to safeguard against accidentally resetting
276 * global service instances that are not yet managed by MediaWikiServices. It is
277 * defined here in the MediaWikiServices services class to have a central place
278 * for managing service bootstrapping and resetting.
280 * @param string $method the name of the caller method, as given by __METHOD__.
282 * @throws MWException if called outside bootstrap mode.
284 * @see resetGlobalInstance()
285 * @see forceGlobalInstance()
286 * @see disableStorageBackend()
288 public static function failIfResetNotAllowed( $method ) {
289 if ( !defined( 'MW_PHPUNIT_TEST' )
290 && !defined( 'MW_PARSER_TEST' )
291 && !defined( 'MEDIAWIKI_INSTALL' )
292 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
293 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
295 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
300 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
301 * This has to contain at least the information needed to set up the 'ConfigFactory'
304 public function __construct( Config
$config ) {
305 parent
::__construct();
307 // Register the given Config object as the bootstrap config service.
308 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
313 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
316 * Returns the Config object containing the bootstrap configuration.
317 * Bootstrap configuration would typically include database credentials
318 * and other information that may be needed before the ConfigFactory
319 * service can be instantiated.
321 * @note This should only be used during bootstrapping, in particular
322 * when creating the MainConfig service. Application logic should
323 * use getMainConfig() to get a Config instances.
327 public function getBootstrapConfig() {
328 return $this->getService( 'BootstrapConfig' );
332 * @return ConfigFactory
334 public function getConfigFactory() {
335 return $this->getService( 'ConfigFactory' );
339 * Returns the Config object that provides configuration for MediaWiki core.
340 * This may or may not be the same object that is returned by getBootstrapConfig().
344 public function getMainConfig() {
345 return $this->getService( 'MainConfig' );
351 public function getSiteLookup() {
352 return $this->getService( 'SiteLookup' );
358 public function getSiteStore() {
359 return $this->getService( 'SiteStore' );
363 * @return StatsdDataFactory
365 public function getStatsdDataFactory() {
366 return $this->getService( 'StatsdDataFactory' );
370 * @return EventRelayerGroup
372 public function getEventRelayerGroup() {
373 return $this->getService( 'EventRelayerGroup' );
377 * @return SearchEngine
379 public function newSearchEngine() {
380 // New engine object every time, since they keep state
381 return $this->getService( 'SearchEngineFactory' )->create();
385 * @return SearchEngineFactory
387 public function getSearchEngineFactory() {
388 return $this->getService( 'SearchEngineFactory' );
392 * @return SearchEngineConfig
394 public function getSearchEngineConfig() {
395 return $this->getService( 'SearchEngineConfig' );
399 * @return SkinFactory
401 public function getSkinFactory() {
402 return $this->getService( 'SkinFactory' );
408 public function getDBLoadBalancerFactory() {
409 return $this->getService( 'DBLoadBalancerFactory' );
413 * @return LoadBalancer The main DB load balancer for the local wiki.
415 public function getDBLoadBalancer() {
416 return $this->getService( 'DBLoadBalancer' );
420 * @return WatchedItemStore
422 public function getWatchedItemStore() {
423 return $this->getService( 'WatchedItemStore' );
428 * @return GenderCache
430 public function getGenderCache() {
431 return $this->getService( 'GenderCache' );
434 ///////////////////////////////////////////////////////////////////////////
435 // NOTE: When adding a service getter here, don't forget to add a test
436 // case for it in MediaWikiServicesTest::provideGetters() and in
437 // MediaWikiServicesTest::provideGetService()!
438 ///////////////////////////////////////////////////////////////////////////