phetit / container
A simple PHP dependency injection container
Requires
- php: ^8.1
- psr/container: 1.1|^2.0
Requires (Dev)
- phpstan/phpstan: ^1.10
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpstan/phpstan-strict-rules: ^1.5
- phpunit/phpunit: ^10.2
- squizlabs/php_codesniffer: ^3.7
Provides
- psr/container-implementation: 1.1|2.0
README
Phetit Container
A simple PHP dependency injection container.
This package is an implementation of PSR-11 container interface, and follows the Semantic Versioning specification.
Installation
You can install it using composer:
composer require phetit/dependency-injection
Usage
Create an instance of ContainerBuilder
class.
use Phetit\DependencyInjection\ContainerBuilder; $container = new ContainerBuilder();
Register a service
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');
Retrieving the service
You can retrieve registered services using the get($id)
method:
$foo = $container->get('foo'); // $foo === 'bar'
Non shared services
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
Parameters
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'
Accessing container from a service
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'), ));
Contributing
Refer to CONTRIBUTING for information.