Reference implementations of the Ioc-Interop interfaces for PHP 8.4+.
composer require ioc-interop/impl
Compose a container by populating a IocContainerFactory with shared instances and service factories, then ask it for a new container:
use IocInterop\Impl\ContainerFactory;
use IocInterop\Interface\IocContainer;
$containerFactory = new ContainerFactory();
$containerFactory->instances = [
PDO::class => new PDO('sqlite::memory:'),
];
$containerFactory->factories = [
Logger::class => fn (IocContainer $ioc) => new Logger(),
UserService::class => fn (IocContainer $ioc) => new UserService(
$ioc->getService(PDO::class),
$ioc->getService(Logger::class),
),
];
$ioc = $containerFactory->newContainer();Retrieve services by name. The first call to getService() resolves and
shares the instance for subsequent calls:
$logger = $ioc->getService(Logger::class);
$users = $ioc->getService(UserService::class);Check for service availability:
if ($ioc->hasService(Logger::class)) {
// ...
}Requesting a service that is not registered throws a ContainerException:
use IocInterop\Interface\IocThrowable;
try {
$ioc->getService('does-not-exist');
} catch (IocThrowable $e) {
// ...
}| Interface | Implementation |
|---|---|
| IocContainer | Container |
| IocContainerFactory | ContainerFactory |
| IocThrowable | ContainerException |
All classes are in the IocInterop\Impl namespace.
See the Ioc-Interop interface package for the full specification.