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

$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() );
    },

];
This article is issued from Mediawiki. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.