/container

Primary LanguagePHPMIT LicenseMIT

Container

Packagist Version Packagist PHP Version Support GitHub Workflow Status

Dependency injection container

example

Install

composer require hyqo/container

Basic usage

For example, we have class Bar, which depends on class Foo:

class Foo {
}

class Bar
{
    private Foo $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

Create container and object of class Bar:

use \Hyqo\Container\Container;

$container = new Container();

$bar = $container->make(Bar::class);
class Bar (1) {
  private Foo $foo =>
  class Foo (0) {
  }
}

Untyped arguments

If class constructor has untyped arguments or type is a built-in type, you must pass an associative array of values to make method.

class Foo {
}

class Bar
{
    private $foo;

    private $arg1;

    private $arg2;

    public function __construct(Foo $foo, int $arg1, $arg2)
    {
        $this->foo = $foo;
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }
}

Create object:

use \Hyqo\Container\Container;

$container = new Container();

$bar = $container->make(Bar::class, ['arg1'=>1, 'arg2'=> 'value']);

Interface mapping

If class constructor required interface implementation, you must bind interface to implementation that be used.

interface FooInterface {
}

class Foo implements FooInterface{
}

class Bar
{
    private $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }
}

Bind interface and create the object:

use \Hyqo\Container\Container;

$container = new Container();
$container->bind(FooInterface::class, Foo::class);

$bar = $container->make(Bar::class);

Constructor configuration

class Bar
{
    public $string;

    public function __construct(string $string)
    {
        $this->string = $string;
    }
}

class Foo {
    private $bar;

    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
    
    public function print() {
        echo $this->bar->string;
    }
}

You can specify object of Bar

use \Hyqo\Container\Container;

$container = new Container();
$container->construct(Foo::class, ['bar'=> new Bar('Hello, world!')]);

$container->make(Foo::class)->print(); //Hello, world!

Or you can specify arguments of Bar to create an object on demand

use \Hyqo\Container\Container;

$container = new Container();
$container->construct(Bar::class, ['string'=>'Hello, world!']);

$container->make(Foo::class)->print(); //Hello, world!

Another way

use \Hyqo\Container\Container;

use function \Hyqo\Container\make;

$container = new Container();
$container->construct(Foo::class, ['bar'=> make(Bar::class, ['string'=>'Hello, world!')])]);

$container->make(Foo::class)->print(); //Hello, world!