corex/container

Simple and Immutable Dependency Injection Container

2.2.0 2023-12-13 09:27 UTC

This package is auto-updated.

Last update: 2024-10-27 15:52:34 UTC


README

license build Code Coverage PHPStan Level

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:

  1. Type-hint ContainerInterface will be resolved to instance of container.
  2. Default parameters specified on definition.
  3. Default parameters in constructor/method.
  4. Specified parameters when calling make() and not already resolved.