Debian Codegraph @

docs/Injection.md

raw symbols SCIP
1 Dependency Injection {#dependencyinjection}
2 =======
3
4 This is an overview of how MediaWiki uses of dependency injection.
5 The design originates from [RFC T384](https://phabricator.wikimedia.org/T384).
6
7 The term "dependency injection" (DI) refers to a pattern in object oriented
8 programming. DI tries to improve modularity by reducing strong coupling
9 between classes. In practical terms, this means that anything an object needs
10 to operate should be injected from the outside. The object itself should only
11 know narrow interfaces, no concrete implementation of the logic it relies on.
12
13 The requirement to inject everything typically results in an architecture based
14 on two main kinds of objects: simple "value" objects with no business logic
15 (and often immutable), and essentially stateless "service" objects that use
16 other service objects to operate on value objects.
17
18 As of 2022 (MediaWiki 1.39), MediaWiki has adopted dependency injection in much
19 of its code. However, some operations still require the use of singletons or
20 otherwise involve global state.
21
22 ## Overview
23
24 The heart of the DI in MediaWiki is the central service locator,
25 MediaWikiServices, which acts as the top-level factory (or registry) for
26 services. MediaWikiServices represents the tree (or network) of service objects
27 that define MediaWiki's application logic. It acts as an entry point to all
28 dependency injection for MediaWiki core.
29
30 When `MediaWikiServices::getInstance()` is first called, it will create an
31 instance of MediaWikiServices and populate it with the services defined by
32 MediaWiki core in `includes/ServiceWiring.php`, as well as any additional
33 bootstrapping files specified in `$wgServiceWiringFiles`. The service
34 wiring files define the (default) service implementations to use, and
35 specifies how they depend on each other ("wiring").
36
37 Extensions can add their own wiring files to `$wgServiceWiringFiles`, in order
38 to define their own service. Extensions may also use the `MediaWikiServices`
39 hook to replace ("redefine") a core service, by calling methods on the
40 MediaWikiServices instance.
41
42 It should be noted that the term "service locator" is often used to refer to a
43 top-level factory that is accessed directly, throughout the code, to avoid
44 explicit dependency injection. In contrast, the term "DI container" is often
45 used to describe a top-level factory that is only accessed only inside service
46 wiring code when instantiating service classes. We use the term "service locator"
47 because it is more descriptive than "DI container", even though application
48 logic is strongly discouraged from accessing MediaWikiServices directly.
49
50 `MediaWikiServices::getInstance()` should ideally be accessed only in "static
51 entry points" such as hook handler functions. See "Migration" below.
52
53 ## Principles {#di-principles}
54
55 Service classes generally only vary on site configuration and are
56 deterministic and agnostic of global state. It is the responsibility of
57 callers to a service object to obtain and derive information from a
58 web request (such as title, user, language, WebRequest, RequestContext),
59 and pass this to specific methods of a service class as-needed. See
60 [T218555](https://phabricator.wikimedia.org/T218555) for related discussion.
61
62 Consider using the factory pattern if your service would otherwise be
63 unergonomic or slow, e.g. due to passing many parameters and/or recomputing
64 the same derived information. This keeps the global state out of the
65 service class, by having the service be a factory from which the caller
66 can obtain a (re-usable) object for its specific context.
67
68 This design ensures service classes are safe to use in both user-facing
69 contexts on the web (e.g. index.php page views and special pages), as
70 well as in an API, job, or maintenance script. It also ensures that
71 within a web-facing context the same service can be safely used
72 multiple times to perform different operations, without incorrectly
73 implying certain commonalities between these calls. Lastly, this
74 restriction allows services to be instantiated across wikis in the
75 future.
76
77 If a feature is not ready to meet these requirements, keep it outside
78 the service container. This avoids false confidence in the safety of an
79 injected service, and its ripple effect on other services.
80
81 ### Principle exemption
82
83 There is a limited exemption to the above principles for "inconsequential
84 state". That is, global state may be used directly if and only if used
85 for diagnostics or to optimise performance, so long as they do not
86 change the observed functional outcome of a called method.
87
88 Examples of safe and inconsequential state:
89
90
91 * Use `$_SERVER['REQUEST_TIME_FLOAT']` or `ConvertibleTimestamp::now`
92 to help compute a time measure that is sent to a metric service.
93
94 * Use `wfHostname()`, `PHP_SAPI`, or `WikiMap::getCurrentWikiId()`
95 to describe where, how, or for which wiki the overall process was
96 created and send it as message context to a logging service.
97
98 * Use `WebRequest::getRequestId()` to automatically inject a
99 header into HTTP requests to other services. These are for tracking
100 purposes only.
101
102 * Use `function_exists('apcu_fetch')` to automatically enable use
103 of caching.
104
105 Examples of unsafe state in a service class:
106
107 * Do not use `WikiMap::getCurrentWikiId()` as the default value
108 to obtain a database connection.
109
110 * Do not use `$_SERVER['SERVER_NAME']` to inject a header into
111 HTTP requests to other services to control which wiki to operate on.
112
113 ## Create a new service
114
115 To create a new service in MediaWiki core, write a function that will return
116 the appropriate class instantiation for that service in ServiceWiring.php. This
117 makes the service available through the generic `getService()` method on the
118 `MediaWikiServices` class. We then also add a wrapper method to
119 MediaWikiServices.php with a discoverable method named and strictly typed
120 return value to reduce mistakes and improve static analysis.
121
122 ## Service Reset
123
124 Services get their configuration injected, and changes to global
125 configuration variables will not have any effect on services that were already
126 instantiated. This would typically be the case for low level services like
127 the ConfigFactory or the ObjectCacheManager, which are used during extension
128 registration. To address this issue, Setup.php resets the global service
129 locator instance by calling `MediaWikiServices::resetGlobalInstance()` once
130 configuration and extension registration is complete.
131
132 Note that "unmanaged" legacy services services that manage their own singleton
133 must not keep references to services managed by MediaWikiServices, to allow a
134 clean reset. After the global MediaWikiServices instance got reset, any such
135 references would be stale, and using a stale service will result in an error.
136
137 Services should either have all dependencies injected and be themselves managed
138 by MediaWikiServices, or they should use the Service Locator pattern, accessing
139 service instances via the global MediaWikiServices instance state when needed.
140 This ensures that no stale service references remain after a reset.
141
142 ## Configuration
143
144 When the default MediaWikiServices instance is created, a Config object is
145 provided to the constructor. This Config object represents the "bootstrap"
146 configuration which will become available as the 'BootstrapConfig' service.
147 As of MW 1.27, the bootstrap config is a GlobalVarConfig object providing
148 access to the $wgXxx configuration variables.
149
150 The bootstrap config is then used to construct a 'ConfigFactory' service,
151 which in turn is used to construct the 'MainConfig' service. Application
152 logic should use the 'MainConfig' service (or a more specific configuration
153 object). 'BootstrapConfig' should only be used for bootstrapping basic
154 services that are needed to load the 'MainConfig'.
155
156 Note: Several well known services in MediaWiki core act as factories
157 themselves, e.g. ApiModuleManager, ObjectCache, SpecialPageFactory, etc.
158 The registries these factories are based on are currently managed as part of
159 the configuration. This may however change in the future.
160
161 ## Migration
162
163 This section provides some recipes for improving code modularity by reducing
164 strong coupling. The dependency injection mechanism described above is an
165 essential tool in this effort.
166
167 ### Migrate access to global service instances and config variables
168 Assume `Foo` is a class that uses the `$wgScriptPath` global and calls
169 `wfGetDB()` to get a database connection, in non-static methods.
170 * Add `$scriptPath` as a constructor parameter and use `$this->scriptPath`
171 instead of `$wgScriptPath`.
172 * Add IConnectionProvider `$dbProvider` as a constructor parameter. Use
173 `$this->dbProvider->getReplicaDatabase()` instead of `wfGetDB( DB_REPLICA )`,
174 `$this->dbProvider->->getPrimaryDatabase()` instead of `wfGetDB( DB_PRIMARY )`.
175 * Any code that calls `Foo`'s constructor would now need to provide the
176 `$scriptPath` and `$dbProvider`. To avoid this, avoid direct instantiation
177 of services all together - see below.
178
179 ### Migrate services with multiple configuration variables
180 When a service needs multiple configuration globals injected, a ServiceOptions
181 object is commonly used with the service class defining a public constant
182 (usually `CONSTRUCTOR_OPTIONS`) with an array of settings that the class needs
183 access to.
184
185 ```php
186 <?php
187
188 class DemoService {
189
190 public const CONSTRUCTOR_OPTIONS = [
191 'Foo',
192 'Bar'
193 ];
194
195 private $options;
196
197 public function __construct( ServiceOptions $options ) {
198 // ServiceOptions::assertRequiredOptions ensures that all of the
199 // settings listed in CONSTRUCTOR_OPTIONS are available
200 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
201 $this->options = $options;
202 // $wgFoo is now available with $this->options->get( 'Foo' )
203 // $wgBar is now available with $this->options->get( 'Bar' )
204 }
205
206 }
207 ```
208
209 ServiceOptions objects are constructed within ServiceWiring.php and can also
210 be created in tests.
211 ```php
212 'DemoService' => function ( MediaWikiServices $services ) : DemoService {
213 return new DemoService(
214 new ServiceOptions(
215 DemoService::CONSTRUCTOR_OPTIONS,
216 $services->getMainConfig()
217 )
218 );
219 },
220 ```
221
222 ### Migrate class-level singleton getters
223 Assume class `Foo` has mostly non-static methods, and provides a static
224 `getInstance()` method that returns a singleton (or default instance).
225 * Add an instantiator function for `Foo` into ServiceWiring.php. The
226 instantiator would do exactly what `Foo::getInstance()` did. However, it
227 should replace any access to global state with calls to `$services->getXxx()`
228 to get a service, or `$services->getMainConfig()->get()` to get a
229 configuration setting.
230 * Add a `getFoo()` method to MediaWikiServices. Don't forget to add the
231 appropriate test cases in MediaWikiServicesTest.
232 * Turn `Foo::getInstance()` into a deprecated alias for
233 `MediaWikiServices::getInstance()->getFoo()`. Change all calls to
234 `Foo::getInstance()` to use injection (see above).
235
236 ### Migrate direct service instantiation
237 Assume class `Bar` calls `new Foo()`.
238 * Add an instantiator function for `Foo` into ServiceWiring.php and add a
239 `getFoo()` method to MediaWikiServices. Don't forget to add the appropriate
240 test cases in MediaWikiServicesTest.
241 * In the instantiator, replace any access to global state with calls
242 to `$services->getXxx()` to get a service, or
243 `$services->getMainConfig()->get()` to get a configuration setting.
244 * The code in `Bar` that calls `Foo`'s constructor should be changed to have a
245 `Foo` instance injected; Eventually, the only code that instantiates `Foo` is
246 the instantiator in ServiceWiring.php.
247 * As an intermediate step, `Bar`'s constructor could initialize the `$foo`
248 member variable by calling `MediaWikiServices::getInstance()->getFoo()`. This
249 is acceptable as a stepping stone, but should be replaced by proper injection
250 via a constructor argument. Do not however inject the MediaWikiServices
251 object!
252
253 ### Migrate parameterized helper instantiation
254 Assume class `Bar` creates some helper object by calling `new Foo( $x )`,
255 and `Foo` uses a global singleton of the `Xyzzy` service.
256 * Define a `FooFactory` class (or a `FooFactory` interface along with a
257 `MyFooFactory` implementation). `FooFactory` defines the method
258 `newFoo( $x )` or `getFoo( $x )`, depending on the desired semantics (`newFoo`
259 would guarantee a fresh instance). When Foo gets refactored to have `Xyzzy`
260 injected, `FooFactory` will need a `Xyzzy` instance, so `newFoo()` can pass it
261 to `new Foo()`.
262 * Add an instantiator function for FooFactory into ServiceWiring.php and add a
263 getFooFactory() method to MediaWikiServices. Don't forget to add the
264 appropriate test cases in MediaWikiServicesTest.
265 * The code in Bar that calls Foo's constructor should be changed to have a
266 FooFactory instance injected; Eventually, the only code that instantiates
267 Foo are implementations of FooFactory, and the only code that instantiates
268 FooFactory is the instantiator in ServiceWiring.php.
269 * As an intermediate step, Bar's constructor could initialize the $fooFactory
270 member variable by calling `MediaWikiServices::getInstance()->getFooFactory()`.
271 This is acceptable as a stepping stone, but should be replaced by proper
272 injection via a constructor argument. Do not however inject the
273 MediaWikiServices object!
274
275 ### Migrate a handler registry
276 Assume class `Bar` calls `FooRegistry::getFoo( $x )` to get a specialized `Foo`
277 instance for handling `$x`.
278 * Turn `getFoo` into a non-static method.
279 * Add an instantiator function for `FooRegistry` into ServiceWiring.php and add
280 a `getFooRegistry()` method to MediaWikiServices. Don't forget to add the
281 appropriate test cases in MediaWikiServicesTest.
282 * Change all code that calls `FooRegistry::getFoo()` statically to call this
283 method on a `FooRegistry` instance. That is, `Bar` would have a `$fooRegistry`
284 member, initialized from a constructor parameter.
285 * As an intermediate step, Bar's constructor could initialize the `$fooRegistry`
286 member variable by calling
287 `MediaWikiServices::getInstance()->getFooRegistry()`. This is acceptable as a
288 stepping stone, but should be replaced by proper injection via a constructor
289 argument. Do not however inject the MediaWikiServices object!
290
291 ### Migrate deferred service instantiation
292 Assume class `Bar` calls `new Foo()`, but only when needed, to avoid the cost of
293 instantiating Foo().
294 * Define a `FooFactory` interface and a `MyFooFactory` implementation of that
295 interface. `FooFactory` defines the method `getFoo()` with no parameters.
296 * Precede as for the "parameterized helper instantiation" case described above.
297
298 ### Migrate a class with only static methods
299 Assume `Foo` is a class with only static methods, such as `frob()`, which
300 interacts with global state or system resources.
301 * Introduce a `FooService` interface and a `DefaultFoo` implementation of that
302 interface. `FooService` contains the public methods defined by Foo.
303 * Add an instantiator function for `FooService` into ServiceWiring.php and
304 add a `getFooService()` method to MediaWikiServices. Don't forget to
305 add the appropriate test cases in MediaWikiServicesTest.
306 * Add a private static `getFooService()` method to `Foo`. That method just
307 calls `MediaWikiServices::getInstance()->getFooService()`.
308 * Make all methods in `Foo` delegate to the `FooService` returned by
309 `getFooService()`. That is, `Foo::frob()` would do
310 `self::getFooService()->frob()`.
311 * Deprecate `Foo`. Inject a `FooService` into all code that calls methods
312 on `Foo`, and change any calls to static methods in foo to the methods
313 provided by the `FooService` interface.
314
315 ### Migrate static hook handler functions (to allow unit testing)
316 Assume `MyExtHooks::onFoo` is a static hook handler function that is called with
317 the parameter `$x`; Further assume `MyExt::onFoo` needs service `Bar`, which is
318 already known to MediaWikiServices (if not, see above).
319 * Create a non-static `doFoo( $x )` method in `MyExtHooks` that has the same
320 signature as `onFoo( $x )`. Move the code from `onFoo()` into `doFoo()`,
321 replacing any access to global or static variables with access to instance
322 member variables.
323 * Add a constructor to `MyExtHooks` that takes a Bar service as a parameter.
324 * Add a static method called `newFromGlobalState()` with no parameters. It
325 should just return
326 `new MyExtHooks( MediaWikiServices::getInstance()->getBar() )`.
327 * The original static handler method `onFoo( $x )` is then implemented as
328 `self::newFromGlobalState()->doFoo( $x )`.
329
330 ### Migrate a "smart record"
331 Assume `Thingy` is a "smart record" that "knows" how to load and store itself.
332 For this purpose, `Thingy` uses wfGetDB().
333 * Create a "dumb" value class `ThingyRecord` that contains all the information
334 that `Thingy` represents (e.g. the information from a database row). The value
335 object should not know about any service.
336 * Create a DAO-style service for loading and storing `ThingyRecord`s, called
337 `ThingyStore`. It may be useful to split the interfaces for reading and
338 writing, with a single class implementing both interfaces, so we in the
339 end have the `ThingyLookup` and `ThingyStore` interfaces, and a SqlThingyStore
340 implementation.
341 * Add instantiator functions for `ThingyLookup` and `ThingyStore` in
342 ServiceWiring.php. Since we want to use the same instance for both service
343 interfaces, the instantiator for `ThingyLookup` would return
344 `$services->getThingyStore()`.
345 * Add `getThingyLookup()` and `getThingyStore()` methods to MediaWikiServices.
346 Don't forget to add the appropriate test cases in MediaWikiServicesTest.
347 * In the old `Thingy` class, replace all member variables that represent the
348 record's data with a single `ThingyRecord` object.
349 * In the old Thingy class, replace all calls to static methods or functions,
350 such as wfGetDB(), with calls to the appropriate services, such as
351 `IConnectionProvider::getReplicaDatabase()`.
352 * In Thingy's constructor, pull in any services needed, such as the
353 IConnectionProvider, by using `MediaWikiServices::getInstance()`. These services
354 cannot be injected without changing the constructor signature, which
355 is often impractical for "smart records" that get instantiated directly
356 in many places in the code base.
357 * Deprecate the old `Thingy` class. Replace all usages of it with one of the
358 three new classes: loading needs a `ThingyLookup`, storing needs a
359 `ThingyStore`, and reading data needs a `ThingyRecord`.
360
361 ### Migrate lazy loading
362 Assume `Thingy` is a "smart record" as described above, but requires lazy
363 loading of some or all the data it represents.
364 * Instead of a plain object, define `ThingyRecord` to be an interface. Provide a
365 "simple" and "lazy" implementations, called `SimpleThingyRecord` and
366 `LazyThingyRecord`. `LazyThingyRecord` knows about some lower level storage
367 interface, like a LoadBalancer, and uses it to load information on demand.
368 * Any direct instantiation of a `ThingyRecord` would use the
369 `SimpleThingyRecord` implementation.
370 * `SqlThingyStore` however creates instances of `LazyThingyRecord`, and injects
371 whatever storage layer service `LazyThingyRecord` needs to perform lazy
372 loading.