phetit/dependency-injection

A simple PHP dependency injection container

v0.7.0 2023-07-27 02:01 UTC

This package is auto-updated.

Last update: 2024-05-30 01:00:21 UTC


README

GitHub release (latest SemVer) Packagist Packagist PHP Version tests GitHub

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.

License

MIT