Services (PHP library)

From mediawiki.org
Jump to navigation Jump to search

Services is a PHP library that provides a generic service container to manage named services using lazy instantiation based on instantiator callback functions. It powers MediaWiki's dependency injection through MediaWikiServices. The library is also compatible with the PSR-11 Container Interface.

Usage[edit]

$services = new ServiceContainer();

$services->defineService(
    'MyService',
    function ( ServiceContainer $services ) {
        return new MyService();
    }
);

$services->loadWiringFiles( [
    'path/to/ServiceWiring.php',
] );

Where ServiceWiring.php looks like this:

return [

    'MyOtherService' => function ( ServiceContainer $services ) {
        return new MyOtherService( $services->get( 'MyService' ) );
    },

    // ...

];

Each instantiator receives the service container as the first argument, from which it may retrieve further services as needed. Additional arguments for each instantiator may be specified when constructing the ServiceContainer. Custom subclasses of ServiceContainer may offer easier access to certain services:

class MyServiceContainer extends ServiceContainer {

    public function getMyService(): MyService {
        return $this->get( 'MyService' );
    }

    public function getMyOtherService(): MyOtherService {
        return $this->get( 'MyOtherService' );
    }

}

// ServiceWiring.php
return [

    'MyOtherService' => function ( MyServiceContainer $services ) {
        return new MyOtherService( $services->getMyService() );
    },

];

External links[edit]