Merge "watcheditem: Fix bad $options param in NoWriteWatchedItemStore::countWatchersM...
[lhc/web/wiklou.git] / docs / injection.txt
1 injection.txt
2
3 This is an overview of how MediaWiki makes use of dependency injection.
4 The design described here grew from the discussion of RFC T384.
5
6
7 The term "dependency injection" (DI) refers to a pattern on object oriented
8 programming that 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 that
14 based on two main types 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 the value objects.
17
18 As of the beginning of 2016 (MW version 1.27), MediaWiki is only starting to
19 use the DI approach. Much of the code still relies on global state or direct
20 instantiation, resulting in a highly cyclical dependency graph.
21
22
23 == Overview ==
24 The heart of the DI in MediaWiki is the central service locator,
25 MediaWikiServices, which acts as the top level factory for services in
26 MediaWiki. MediaWikiServices::getInstance() returns the default service
27 locator instance, which can be used to gain access to default instances of
28 various services. MediaWikiServices however also allows new services to be
29 defined and default services to be redefined. Services are defined or
30 redefined by providing a callback function, the "instantiator" function,
31 that will return a new instance of the service.
32
33 When MediaWikiServices::getInstance() is first called, it will create an
34 instance of MediaWikiServices and populate it with the services defined
35 in the files listed by $wgServiceWiringFiles, thereby "bootstrapping" the
36 DI framework. Per default, $wgServiceWiringFiles lists
37 includes/ServiceWiring.php, which defines all default service
38 implementations, and specifies how they depend on each other ("wiring").
39
40 When a new service is added to MediaWiki core, an instantiator function
41 that will create the appropriate default instance for that service must
42 be added to ServiceWiring.php. This makes the service available through
43 the generic getService() method on the service locator returned by
44 MediaWikiServices::getInstance().
45
46 Extensions can add their own wiring files to $wgServiceWiringFiles, in order
47 to define their own service. Extensions may also use the 'MediaWikiServices'
48 hook to define or redefined services by calling methods on the default
49 MediaWikiServices instance.
50
51
52 It should be noted that the term "service locator" is often used to refer to a
53 top level factory that is accessed directly, throughout the code, to avoid
54 explicit dependency injection. In contrast, the term "DI container" is often
55 used to describe a top level factory that is only accessed when services
56 are created. We use the term "service locator" for the top level factory
57 because it is more descriptive than "DI container", even though application
58 logic is strongly discouraged from accessing MediaWikiServices directly.
59 MediaWikiServices::getInstance() should ideally be accessed only in "static
60 entry points" such as hook handler functions. See "Migration" below.
61
62
63 == Service Reset ==
64
65 Services get their configuration injected, and changes to global
66 configuration variables will not have any effect on services that were already
67 instantiated. This would typically be the case for low level services like
68 the ConfigFactory or the ObjectCacheManager, which are used during extension
69 registration. To address this issue, Setup.php resets the global service
70 locator instance by calling MediaWikiServices::resetGlobalInstance() once
71 configuration and extension registration is complete.
72
73 Note that "unmanaged" legacy services services that manage their own singleton
74 must not keep references to services managed by MediaWikiServices, to allow a
75 clean reset. After the global MediaWikiServices instance got reset, any such
76 references would be stale, and using a stale service will result in an error.
77
78 Services should either have all dependencies injected and be themselves managed
79 by MediaWikiServices, or they should use the Service Locator pattern, accessing
80 service instances via the global MediaWikiServices instance state when needed.
81 This ensures that no stale service references remain after a reset.
82
83
84 == Configuration ==
85
86 When the default MediaWikiServices instance is created, a Config object is
87 provided to the constructor. This Config object represents the "bootstrap"
88 configuration which will become available as the 'BootstrapConfig' service.
89 As of MW 1.27, the bootstrap config is a GlobalVarConfig object providing
90 access to the $wgXxx configuration variables.
91
92 The bootstrap config is then used to construct a 'ConfigFactory' service,
93 which in turn is used to construct the 'MainConfig' service. Application
94 logic should use the 'MainConfig' service (or a more specific configuration
95 object). 'BootstrapConfig' should only be used for bootstrapping basic
96 services that are needed to load the 'MainConfig'.
97
98
99 Note: Several well known services in MediaWiki core act as factories
100 themselves, e.g. ApiModuleManager, ObjectCache, SpecialPageFactory, etc.
101 The registries these factories are based on are currently managed as part of
102 the configuration. This may however change in the future.
103
104
105 == Migration ==
106
107 This section provides some recipes for improving code modularity by reducing
108 strong coupling. The dependency injection mechanism described above is an
109 essential tool in this effort.
110
111 Migrate access to global service instances and config variables:
112 Assume Foo is a class that uses the $wgScriptPath global and calls
113 wfGetDB() to get a database connection, in non-static methods.
114 * Add $scriptPath as a constructor parameter and use $this->scriptPath
115 instead of $wgScriptPath.
116 * Add LoadBalancer $dbLoadBalancer as a constructor parameter. Use
117 $this->dbLoadBalancer->getConnection() instead of wfGetDB().
118 * Any code that calls Foo's constructor would now need to provide the
119 $scriptPath and $dbLoadBalancer. To avoid this, avoid direct instantiation
120 of services all together - see below.
121
122 Migrate class-level singleton getters:
123 Assume class Foo has mostly non-static methods, and provides a static
124 getInstance() method that returns a singleton (or default instance).
125 * Add an instantiator function for Foo into ServiceWiring.php. The instantiator
126 would do exactly what Foo::getInstance() did. However, it should
127 replace any access to global state with calls to $services->getXxx() to get a
128 service, or $services->getMainConfig()->get() to get a configuration setting.
129 * Add a getFoo() method to MediaWikiServices. Don't forget to add the
130 appropriate test cases in MediaWikiServicesTest.
131 * Turn Foo::getInstance() into a deprecated alias for
132 MediaWikiServices::getInstance()->getFoo(). Change all calls to
133 Foo::getInstance() to use injection (see above).
134
135 Migrate direct service instantiation:
136 Assume class Bar calls new Foo().
137 * Add an instantiator function for Foo into ServiceWiring.php and add a getFoo()
138 method to MediaWikiServices. Don't forget to add the appropriate test cases
139 in MediaWikiServicesTest.
140 * In the instantiator, replace any access to global state with calls
141 to $services->getXxx() to get a service, or $services->getMainConfig()->get()
142 to get a configuration setting.
143 * The code in Bar that calls Foo's constructor should be changed to have a Foo
144 instance injected; Eventually, the only code that instantiates Foo is the
145 instantiator in ServiceWiring.php.
146 * As an intermediate step, Bar's constructor could initialize the $foo member
147 variable by calling MediaWikiServices::getInstance()->getFoo(). This is
148 acceptable as a stepping stone, but should be replaced by proper injection
149 via a constructor argument. Do not however inject the MediaWikiServices
150 object!
151
152 Migrate parameterized helper instantiation:
153 Assume class Bar creates some helper object by calling new Foo( $x ),
154 and Foo uses a global singleton of the Xyzzy service.
155 * Define a FooFactory class (or a FooFactory interface along with a MyFooFactory
156 implementation). FooFactory defines the method newFoo( $x ) or getFoo( $x ),
157 depending on the desired semantics (newFoo would guarantee a fresh instance).
158 When Foo gets refactored to have Xyzzy injected, FooFactory will need a
159 Xyzzy instance, so newFoo() can pass it to new Foo().
160 * Add an instantiator function for FooFactory into ServiceWiring.php and add a
161 getFooFactory() method to MediaWikiServices. Don't forget to add the
162 appropriate test cases in MediaWikiServicesTest.
163 * The code in Bar that calls Foo's constructor should be changed to have a
164 FooFactory instance injected; Eventually, the only code that instantiates
165 Foo are implementations of FooFactory, and the only code that instantiates
166 FooFactory is the instantiator in ServiceWiring.php.
167 * As an intermediate step, Bar's constructor could initialize the $fooFactory
168 member variable by calling MediaWikiServices::getInstance()->getFooFactory().
169 This is acceptable as a stepping stone, but should be replaced by proper
170 injection via a constructor argument. Do not however inject the
171 MediaWikiServices object!
172
173 Migrate a handler registry:
174 Assume class Bar calls FooRegistry::getFoo( $x ) to get a specialized Foo
175 instance for handling $x.
176 * Turn getFoo into a non-static method.
177 * Add an instantiator function for FooRegistry into ServiceWiring.php and add
178 a getFooRegistry() method to MediaWikiServices. Don't forget to add the
179 appropriate test cases in MediaWikiServicesTest.
180 * Change all code that calls FooRegistry::getFoo() statically to call this
181 method on a FooRegistry instance. That is, Bar would have a $fooRegistry
182 member, initialized from a constructor parameter.
183 * As an intermediate step, Bar's constructor could initialize the $fooRegistry
184 member variable by calling MediaWikiServices::getInstance()->
185 getFooRegistry(). This is acceptable as a stepping stone, but should be
186 replaced by proper injection via a constructor argument. Do not however
187 inject the MediaWikiServices object!
188
189 Migrate deferred service instantiation:
190 Assume class Bar calls new Foo(), but only when needed, to avoid the cost of
191 instantiating Foo().
192 * Define a FooFactory interface and a MyFooFactory implementation of that
193 interface. FooFactory defines the method getFoo() with no parameters.
194 * Precede as for the "parameterized helper instantiation" case described above.
195
196 Migrate a class with only static methods:
197 Assume Foo is a class with only static methods, such as frob(), which
198 interacts with global state or system resources.
199 * Introduce a FooService interface and a DefaultFoo implementation of that
200 interface. FooService contains the public methods defined by Foo.
201 * Add an instantiator function for FooService into ServiceWiring.php and
202 add a getFooService() method to MediaWikiServices. Don't forget to
203 add the appropriate test cases in MediaWikiServicesTest.
204 * Add a private static getFooService() method to Foo. That method just
205 calls MediaWikiServices::getInstance()->getFooService().
206 * Make all methods in Foo delegate to the FooService returned by
207 getFooService(). That is, Foo::frob() would do self::getFooService()->frob().
208 * Deprecate Foo. Inject a FooService into all code that calls methods
209 on Foo, and change any calls to static methods in foo to the methods
210 provided by the FooService interface.
211
212 Migrate static hook handler functions (to allow unit testing):
213 Assume MyExtHooks::onFoo is a static hook handler function that is called with
214 the parameter $x; Further assume MyExt::onFoo needs service Bar, which is
215 already known to MediaWikiServices (if not, see above).
216 * Create a non-static doFoo( $x ) method in MyExtHooks that has the same
217 signature as onFoo( $x ). Move the code from onFoo() into doFoo(), replacing
218 any access to global or static variables with access to instance member
219 variables.
220 * Add a constructor to MyExtHooks that takes a Bar service as a parameter.
221 * Add a static method called newFromGlobalState() with no parameters. It should
222 just return new MyExtHooks( MediaWikiServices::getInstance()->getBar() ).
223 * The original static handler method onFoo( $x ) is then implemented as
224 self::newFromGlobalState()->doFoo( $x ).
225
226 Migrate a "smart record":
227 Assume Thingy is a "smart record" that "knows" how to load and store itself.
228 For this purpose, Thingy uses wfGetDB().
229 * Create a "dumb" value class ThingyRecord that contains all the information
230 that Thingy represents (e.g. the information from a database row). The value
231 object should not know about any service.
232 * Create a DAO-style service for loading and storing ThingyRecords, called
233 ThingyStore. It may be useful to split the interfaces for reading and
234 writing, with a single class implementing both interfaces, so we in the
235 end have the ThingyLookup and ThingyStore interfaces, and a SqlThingyStore
236 implementation.
237 * Add instantiator functions for ThingyLookup and ThingyStore in
238 ServiceWiring.php. Since we want to use the same instance for both service
239 interfaces, the instantiator for ThingyLookup would return
240 $services->getThingyStore().
241 * Add getThingyLookup() and getThingyStore methods to MediaWikiServices.
242 Don't forget to add the appropriate test cases in MediaWikiServicesTest.
243 * In the old Thingy class, replace all member variables that represent the
244 record's data with a single ThingyRecord object.
245 * In the old Thingy class, replace all calls to static methods or functions,
246 such as wfGetDB(), with calls to the appropriate services, such as
247 LoadBalancer::getConnection().
248 * In Thingy's constructor, pull in any services needed, such as the
249 LoadBalancer, by using MediaWikiServices::getInstance(). These services
250 cannot be injected without changing the constructor signature, which
251 is often impractical for "smart records" that get instantiated directly
252 in many places in the code base.
253 * Deprecate the old Thingy class. Replace all usages of it with one of the
254 three new classes: loading needs a ThingyLookup, storing needs a ThingyStore,
255 and reading data needs a ThingyRecord.
256
257 Migrate lazy loading:
258 Assume Thingy is a "smart record" as described above, but requires lazy loading
259 of some or all the data it represents.
260 * Instead of a plain object, define ThingyRecord to be an interface. Provide a
261 "simple" and "lazy" implementations, called SimpleThingyRecord and
262 LazyThingyRecord. LazyThingyRecord knows about some lower level storage
263 interface, like a LoadBalancer, and uses it to load information on demand.
264 * Any direct instantiation of a ThingyRecord would use the SimpleThingyRecord
265 implementation.
266 * SqlThingyStore however creates instances of LazyThingyRecord, and injects
267 whatever storage layer service LazyThingyRecord needs to perform lazy loading.
268
269