A simple PHP dependency injection container.
This package is an implementation of PSR-11 container interface, and follows the Semantic Versioning specification.
You can install it using composer:
composer require phetit/dependency-injection
Create an instance of ContainerBuilder
class.
use Phetit\DependencyInjection\ContainerBuilder;
$container = new ContainerBuilder();
You can register a service using the register($id, $resolver)
method, and passing the id
(string) and the resolver
(a closure).
$container->register('foo', fn() => 'bar');
You can retrieve registered services using the get($id)
method:
$foo = $container->get('foo');
// $foo === 'bar'
By default all services are shared. This means that services are resolved only the first time get($id)
method is called. So in following calls you'll get the same object.
$container->register('service', fn() => new Service());
$serviceOne = $container->get('service'); // Service object
$serviceTwo = $container->get('service'); // Service object
// $serviceOne === $serviceTwo => true
In order to get a new instance on every call, you need to use the factory()
method:
$container->factory('service', fn() => new Service());
$serviceOne = $container->get('service'); // Service object
$serviceTwo = $container->get('service'); // Service object
// $serviceOne === $serviceTwo => false
You can register parameters using parameter()
method:
$container->parameter('foo', 'bar');
$container->parameter('closure', fn() => new Service());
$container->get('foo'); // 'bar'
// Parameters are not resolved
$closure = $container->get('closure'); // $closure = fn() => new Service()
$service = $closure(); // 'Service object'
Container object is injected to service resolvers, so you can access other entries defined in the container:
$container->parameter('db_dns', 'mysql:dbname=testdb;host=127.0.0.1');
$container->parameter('db_user', 'dbuser');
$container->parameter('db_pass', 'dbpass');
$container->register('db', fn(Container $c) => new PDO(
$c->get('db_dns'),
$c->get('db_user'),
$c->get('db_pass'),
));
Refer to CONTRIBUTING for information.