Jump to content
MediaWiki

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 ) as well as extension.json . 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' )

Optional service dependencies

[edit ]
MediaWiki version:
≥ 1.36

Starting with MediaWiki 1.36 , service dependencies can be made optional by using the optional_services key. This is useful when an extension wants to offer optional integration with another extension. In that situation, extension A could declare an optional service in an object specification in its extension.json that references a service defined by extension B. If that service was not defined because extension B is not loaded, an entry in services would raise an error (NoSuchServiceException) while an entry in optional_services will evaluate to null.

In extension A, define the service in extension.json with the service from B under optional_services:

{
"class":"ExtensionA\\MyClass",
"services":["CoreService"],
"optional_services":["ExtensionBService"]
}

You would then first check for the service existence (has()) and then get the service:

$services = \MediaWiki\MediaWikiServices::getInstance();
new MyClass(
 $services->get( 'CoreService' ),
 $services->has( 'ExtensionBService' )
 ? $services->get( 'ExtensionBService' ) : null
);
[edit ]

AltStyle によって変換されたページ (->オリジナル) /