tbachert / spi
Service provider loading facility
Installs: 1 236 024
Dependents: 5
Suggesters: 2
Security: 0
Stars: 3
Watchers: 1
Forks: 2
Open Issues: 1
Type:composer-plugin
Requires
- php: ^8.1
- composer-plugin-api: ^2.0
- composer/semver: ^1.0 || ^2.0 || ^3.0
Requires (Dev)
- composer/composer: ^2.0
- infection/infection: ^0.27.9
- phpunit/phpunit: ^10.5
- psalm/phar: ^5.18
README
Service provider loading facility, inspired by Javas ServiceLoader
.
Install
composer require tbachert/spi
Usage
Registering service providers
Service provider implementations must provide a public zero-arguments constructor.
Registering via composer.json extra.spi
composer config --json --merge extra.spi.Example\\Service '["Example\\Implementation"]'
Registering via php
ServiceLoader::register(Example\Service::class, Example\Implementation::class);
Converting ServiceLoader::register()
calls to precompiled map
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
Removing obsolete entries from autoload.files
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
.
Application authors
Make sure to allow the composer plugin to be able to load service providers.
composer config allow-plugins.tbachert/spi true
Loading service providers
foreach (ServiceLoader::load('Namespace\Service') as $provider) { // ... }
Handling invalid service configurations
$loader = ServiceLoader::load('Namespace\Service'); for ($it = $loader->getIterator(); $it->valid(); $it->next()) { try { $provider = $it->current(); } catch (ServiceConfigurationError) {} }