Type-hint your constructor parameters and the container can guess which dependencies to inject.
class Foo
{
private $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
Covers 80% of the use cases with 0 configuration.
PHP-DI's configuration is written in PHP, allowing to benefit from auto-completion, static analysis and refactoring support with any IDE.
return [
Foo::class => create()
->constructor(
get(Bar::class)
)
];
return [
Foo::class => function ($container) {
$bar = $container->get(Bar::class);
return new Foo($bar);
}
];
return [
NotifierInterface::class => get(EmailNotifier::class)
];
return [
'db.host' => env('DB_HOST', 'default value')
];
The configuration format has been imagined as a successor of XML and YAML, taking advantages of all the latest features of PHP:
return [
];
::class
magic constantreturn [
Foo::class => DI\create()
->constructor(DI\get(Bar::class))
];
use function
return [
Foo::class => create()
->constructor(get(Bar::class))
];
Just create the container and you are good to go thanks to autowiring.
$container = new Container();
$home = $container->get(HomeController::class);
You can also define services à la Pimple:
$container->set('db', new Database($options));
$container->set('logger', function () {
$logger = new Monolog\Logger();
$logger->pushHandler(new StreamHandler('app.log'));
return $logger;
});
$db = $container->get('db');
$logger = $container->get('logger');
Register as many configuration files as you want.
// base config
return [
'notifiers' => [
get(EmailNotifier::class),
]
];
Use definition overriding to extend lists, decorate or replace previous entries…
// module (aka bundle) config
return [
'notifiers' => add([
get(TextNotifier::class),
get(MobilePushNotifier::class),
])
];
PHP-DI provides the classic API of a container as well as advanced features useful to build or extend a framework.
PHP-DI is compliant with PSR-11:
$container->get($name);
$container->has($name);
Use the container as a factory:
$parameters = [ ... ];
$container->make(Foo::class, $parameters);
Missing constructor parameters will be resolved from the container.
Dependency injection in callables, à la AngularJS:
$container->call(function (Logger $logger, EntityManager $em) {
// ...
});
PHP-DI integrates easily in your application or in frameworks.
No framework? It works too, have a look at this demo application.