Injection.md - document ServiceOptions/CONSTRUCTOR_OPTIONS systems

Common way of injecting multiple configuration values

Change-Id: Ie7f7febf279baf34bad8b628911285bca3a008b5
This commit is contained in:
DannyS712 2020-05-25 10:19:44 +00:00
parent 7c645c4c95
commit e55e19c630

View file

@ -120,6 +120,49 @@ Assume `Foo` is a class that uses the `$wgScriptPath` global and calls
`$scriptPath` and `$dbLoadBalancer`. To avoid this, avoid direct instantiation
of services all together - see below.
### Migrate services with multiple configuration variables
When a service needs multiple configuration globals injected, a ServiceOptions
object is commonly used with the service class defining a public constant
(usually `CONSTRUCTOR_OPTIONS`) with an array of settings that the class needs
access to.
```php
<?php
class DemoService {
public const CONSTRUCTOR_OPTIONS = [
'Foo',
'Bar'
];
private $options;
public function __construct( ServiceOptions $options ) {
// ServiceOptions::assertRequiredOptions ensures that all of the
// settings listed in CONSTRUCTOR_OPTIONS are available
$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
$this->options = $options;
// $wgFoo is now available with $this->options->get( 'Foo' )
// $wgBar is now available with $this->options->get( 'Bar' )
}
}
```
ServiceOptions objects are constructed within ServiceWiring.php and can also
be created in tests.
```php
'DemoService' => function ( MediaWikiServices $services ) : DemoService {
return new DemoService(
new ServiceOptions(
DemoService::CONSTRUCTOR_OPTIONS,
$services->getMainConfig()
)
);
},
```
### Migrate class-level singleton getters
Assume class `Foo` has mostly non-static methods, and provides a static
`getInstance()` method that returns a singleton (or default instance).