Service provider loading facility, inspired by Javas ServiceLoader
.
composer require tbachert/spi
Service provider implementations must provide a public zero-arguments constructor.
composer config --json --merge extra.spi.Example\\Service '["Example\\Implementation"]'
ServiceLoader::register(Example\Service::class, Example\Implementation::class);
ServiceLoader::register()
calls can be converted to a precompiled map by setting extra.spi-config.autoload-files
to
true
to process allautoload.files
(should be used iffautoload.files
is used exclusively for service provider registration),- or a list of files that register service providers.
composer config --json extra.spi-config.autoload-files true
By default, extra.spi-config.autoload-files
files that register service providers are removed from
autoload.files
. This behavior can be configured by setting extra.spi-config.prune-autoload-files
to
true
to remove allexra.spi-config.autoload-files
files fromautoload.files
,false
to keep allautoload.files
entries,- or a list of files that should be removed from
autoload.files
.
Make sure to allow the composer plugin to be able to load service providers.
composer config allow-plugins.tbachert/spi true
foreach (ServiceLoader::load('Namespace\Service') as $provider) {
// ...
}
$loader = ServiceLoader::load('Namespace\Service');
for ($it = $loader->getIterator(); $it->valid(); $it->next()) {
try {
$provider = $it->current();
} catch (ServiceConfigurationError) {}
}