Jump to content

ObjectFactory

From mediawiki.org

ObjectFactory creates objects from specifications (via $objectFactory->createObject() or ObjectFactory::getObjectFromSpec()). This format is used by certain configuration settings (such as $wgMWLoggerDefaultSpi or $wgSessionProviders ). A typical specification looks like this:

$spec = [
    'class' => 'Message',
    'args' => [ 'unexpected', [ 'foo', 123 ] ],
];

which is the specification for new Message( 'unexpected', [ 'foo', 123 ] ).

Other options include:

$spec = [
    'factory' => 'Message::newFallbackSequence',
    'args' => [ 'unexpected', 'unexpected2' ],
];
// Message::newFallbackSequence( 'unexpected', 'unexpected2' )
$spec = [
    'class' => 'Message',
    'args' => [ 'foo', 'bar' ],
    'calls' => [ 'inLanguage' => [ 'en' ], 'useDatabase' => [ false ] ],
];
// will call $message->inLanguage( 'en' ), $message->useDatabase( false ) after creating $message
MediaWiki version:
1.34

Starting with MediaWiki 1.34 , ObjectFactory now supports creating classes with services specified in the spec. To use ObjectFactory to create classes that need services, you'll need to use the ObjectFactory service, and call the createObject method.

For non-MediaWiki uses, an ObjectFactory instance can be created with a PSR-11 Container interface that will be used to retrieve the services.

$spec = [
    'class' => 'MyClass',
    'args' => [ 'foo', 'bar' ],
    'services' => [ 'Service1', 'Service2' ],
];
// $services = \MediaWiki\MediaWikiServices::getInstance();
// new MyClass( $services->get( 'Service1' ), $services->get( 'Service2' ), 'foo', 'bar' )
[edit]