corex / container
Simple and Immutable Dependency Injection Container
2.2.0
2023-12-13 09:27 UTC
Requires
- php: ^8.1
- psr/container: ^2.0
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-10-27 15:52:34 UTC
README
Breaking changes - this package has been rewritten from scratch to be more strict and simple to use.
- Container is immutable.
- Support for PSR-11 Container Interface.
- Support for setting default parameters on definitions.
A few examples
Make a class without binding.
$myClass = (new Container())->make(MyClass::class);
Type-hints will be resolved if they are bound in advance.
Make a class with binding and parameters.
$containerBuilder = new ContainerBuilder(); $containerBuilder->bind('myClass', MyClass::class) ->setArgument('firstname', 'Roger'); $container = new Container($containerBuilder); $myClass = $container->make('myClass', [ 'lastname' => 'Moore' ]);
Make a class binding by class.
$containerBuilder = new ContainerBuilder(); $containerBuilder->bindClass(MyClass::class); $container = new Container($containerBuilder); $myClass = $container->get(MyClass::class);
Make a class binding by implemented interface.
interface MyClassInterface { } class MyClass implements MyClassInterface { } $containerBuilder = new ContainerBuilder(); $containerBuilder->bindClassOnInterface(MyClass::class); $container = new Container($containerBuilder); $myClass = $container->get(MyClassInterface::class);
Parameters
Parameters will be resolved in following order:
- Type-hint ContainerInterface will be resolved to instance of container.
- Default parameters specified on definition.
- Default parameters in constructor/method.
- Specified parameters when calling make() and not already resolved.