ba3ab3253b2fd5e186d79734a079d02a13e265dc
[lhc/web/wiklou.git] / includes / Services / ServiceContainer.php
1 <?php
2 namespace MediaWiki\Services;
3
4 use InvalidArgumentException;
5 use RuntimeException;
6 use Wikimedia\Assert\Assert;
7
8 /**
9 * Generic service container.
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 *
26 * @file
27 *
28 * @since 1.27
29 */
30
31 /**
32 * ServiceContainer provides a generic service to manage named services using
33 * lazy instantiation based on instantiator callback functions.
34 *
35 * Services managed by an instance of ServiceContainer may or may not implement
36 * a common interface.
37 *
38 * @note When using ServiceContainer to manage a set of services, consider
39 * creating a wrapper or a subclass that provides access to the services via
40 * getter methods with more meaningful names and more specific return type
41 * declarations.
42 *
43 * @see docs/injection.txt for an overview of using dependency injection in the
44 * MediaWiki code base.
45 */
46 class ServiceContainer implements DestructibleService {
47
48 /**
49 * @var object[]
50 */
51 private $services = [];
52
53 /**
54 * @var callable[]
55 */
56 private $serviceInstantiators = [];
57
58 /**
59 * @var array
60 */
61 private $extraInstantiationParams;
62
63 /**
64 * @var boolean
65 */
66 private $destroyed = false;
67
68 /**
69 * @param array $extraInstantiationParams Any additional parameters to be passed to the
70 * instantiator function when creating a service. This is typically used to provide
71 * access to additional ServiceContainers or Config objects.
72 */
73 public function __construct( array $extraInstantiationParams = [] ) {
74 $this->extraInstantiationParams = $extraInstantiationParams;
75 }
76
77 /**
78 * Destroys all contained service instances that implement the DestructibleService
79 * interface. This will render all services obtained from this MediaWikiServices
80 * instance unusable. In particular, this will disable access to the storage backend
81 * via any of these services. Any future call to getService() will throw an exception.
82 *
83 * @see resetGlobalInstance()
84 */
85 public function destroy() {
86 foreach ( $this->getServiceNames() as $name ) {
87 $service = $this->peekService( $name );
88 if ( $service !== null && $service instanceof DestructibleService ) {
89 $service->destroy();
90 }
91 }
92
93 $this->destroyed = true;
94 }
95
96 /**
97 * @param array $wiringFiles A list of PHP files to load wiring information from.
98 * Each file is loaded using PHP's include mechanism. Each file is expected to
99 * return an associative array that maps service names to instantiator functions.
100 */
101 public function loadWiringFiles( array $wiringFiles ) {
102 foreach ( $wiringFiles as $file ) {
103 // the wiring file is required to return an array of instantiators.
104 $wiring = require $file;
105
106 Assert::postcondition(
107 is_array( $wiring ),
108 "Wiring file $file is expected to return an array!"
109 );
110
111 $this->applyWiring( $wiring );
112 }
113 }
114
115 /**
116 * Registers multiple services (aka a "wiring").
117 *
118 * @param array $serviceInstantiators An associative array mapping service names to
119 * instantiator functions.
120 */
121 public function applyWiring( array $serviceInstantiators ) {
122 Assert::parameterElementType( 'callable', $serviceInstantiators, '$serviceInstantiators' );
123
124 foreach ( $serviceInstantiators as $name => $instantiator ) {
125 $this->defineService( $name, $instantiator );
126 }
127 }
128
129 /**
130 * Returns true if a service is defined for $name, that is, if a call to getService( $name )
131 * would return a service instance.
132 *
133 * @param string $name
134 *
135 * @return bool
136 */
137 public function hasService( $name ) {
138 return isset( $this->serviceInstantiators[$name] );
139 }
140
141 /**
142 * Returns the service instance for $name only if that service has already been instantiated.
143 * This is intended for situations where services get destroyed/cleaned up, so we can
144 * avoid creating a service just to destroy it again.
145 *
146 * @note Application logic should use getService() instead.
147 *
148 * @see getService().
149 *
150 * @param string $name
151 *
152 * @return object|null The service instance, or null if the service has not yet been instantiated.
153 * @throws RuntimeException if $name does not refer to a known service.
154 */
155 public function peekService( $name ) {
156 if ( !$this->hasService( $name ) ) {
157 throw new NoSuchServiceException( $name );
158 }
159
160 return isset( $this->services[$name] ) ? $this->services[$name] : null;
161 }
162
163 /**
164 * @return string[]
165 */
166 public function getServiceNames() {
167 return array_keys( $this->serviceInstantiators );
168 }
169
170 /**
171 * Define a new service. The service must not be known already.
172 *
173 * @see getService().
174 * @see replaceService().
175 *
176 * @param string $name The name of the service to register, for use with getService().
177 * @param callable $instantiator Callback that returns a service instance.
178 * Will be called with this MediaWikiServices instance as the only parameter.
179 * Any extra instantiation parameters provided to the constructor will be
180 * passed as subsequent parameters when invoking the instantiator.
181 *
182 * @throws RuntimeException if there is already a service registered as $name.
183 */
184 public function defineService( $name, callable $instantiator ) {
185 Assert::parameterType( 'string', $name, '$name' );
186
187 if ( $this->hasService( $name ) ) {
188 throw new ServiceAlreadyDefinedException( $name );
189 }
190
191 $this->serviceInstantiators[$name] = $instantiator;
192 }
193
194 /**
195 * Replace an already defined service.
196 *
197 * @see defineService().
198 *
199 * @note This causes any previously instantiated instance of the service to be discarded.
200 *
201 * @param string $name The name of the service to register.
202 * @param callable $instantiator Callback function that returns a service instance.
203 * Will be called with this MediaWikiServices instance as the only parameter.
204 * The instantiator must return a service compatible with the originally defined service.
205 * Any extra instantiation parameters provided to the constructor will be
206 * passed as subsequent parameters when invoking the instantiator.
207 *
208 * @throws RuntimeException if $name is not a known service.
209 */
210 public function redefineService( $name, callable $instantiator ) {
211 Assert::parameterType( 'string', $name, '$name' );
212
213 if ( !$this->hasService( $name ) ) {
214 throw new NoSuchServiceException( $name );
215 }
216
217 if ( isset( $this->services[$name] ) ) {
218 throw new CannotReplaceActiveServiceException( $name );
219 }
220
221 $this->serviceInstantiators[$name] = $instantiator;
222 }
223
224 /**
225 * Disables a service.
226 *
227 * @note Attempts to call getService() for a disabled service will result
228 * in a DisabledServiceException. Calling peekService for a disabled service will
229 * return null. Disabled services are listed by getServiceNames(). A disabled service
230 * can be enabled again using redefineService().
231 *
232 * @note If the service was already active (that is, instantiated) when getting disabled,
233 * and the service instance implements DestructibleService, destroy() is called on the
234 * service instance.
235 *
236 * @see redefineService()
237 * @see resetService()
238 *
239 * @param string $name The name of the service to disable.
240 *
241 * @throws RuntimeException if $name is not a known service.
242 */
243 public function disableService( $name ) {
244 $this->resetService( $name );
245
246 $this->redefineService( $name, function() use ( $name ) {
247 throw new ServiceDisabledException( $name );
248 } );
249 }
250
251 /**
252 * Resets a service by dropping the service instance.
253 * If the service instances implements DestructibleService, destroy()
254 * is called on the service instance.
255 *
256 * @warning This is generally unsafe! Other services may still retain references
257 * to the stale service instance, leading to failures and inconsistencies. Subclasses
258 * may use this method to reset specific services under specific instances, but
259 * it should not be exposed to application logic.
260 *
261 * @note This is declared final so subclasses can not interfere with the expectations
262 * disableService() has when calling resetService().
263 *
264 * @see redefineService()
265 * @see disableService().
266 *
267 * @param string $name The name of the service to reset.
268 * @param bool $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.
271 *
272 * @throws RuntimeException if $name is not a known service.
273 */
274 final protected function resetService( $name, $destroy = true ) {
275 Assert::parameterType( 'string', $name, '$name' );
276
277 $instance = $this->peekService( $name );
278
279 if ( $destroy && $instance instanceof DestructibleService ) {
280 $instance->destroy();
281 }
282
283 unset( $this->services[$name] );
284 }
285
286 /**
287 * Returns a service object of the kind associated with $name.
288 * Services instances are instantiated lazily, on demand.
289 * This method may or may not return the same service instance
290 * when called multiple times with the same $name.
291 *
292 * @note Rather than calling this method directly, it is recommended to provide
293 * getters with more meaningful names and more specific return types, using
294 * a subclass or wrapper.
295 *
296 * @see redefineService().
297 *
298 * @param string $name The service name
299 *
300 * @throws NoSuchServiceException if $name is not a known service.
301 * @throws ServiceDisabledException if this container has already been destroyed.
302 *
303 * @return object The service instance
304 */
305 public function getService( $name ) {
306 if ( $this->destroyed ) {
307 throw new ContainerDisabledException();
308 }
309
310 if ( !isset( $this->services[$name] ) ) {
311 $this->services[$name] = $this->createService( $name );
312 }
313
314 return $this->services[$name];
315 }
316
317 /**
318 * @param string $name
319 *
320 * @throws InvalidArgumentException if $name is not a known service.
321 * @return object
322 */
323 private function createService( $name ) {
324 if ( isset( $this->serviceInstantiators[$name] ) ) {
325 $service = call_user_func_array(
326 $this->serviceInstantiators[$name],
327 array_merge( [ $this ], $this->extraInstantiationParams )
328 );
329 } else {
330 throw new NoSuchServiceException( $name );
331 }
332
333 return $service;
334 }
335
336 }