flashytime/container

A lightweight PHP dependency injection container.

v1.0.0 2018-07-11 13:33 UTC

This package is not auto-updated.

Last update: 2024-05-10 08:19:16 UTC


README

A lightweight PHP dependency injection container.

Installation

composer require flashytime/container

Usage

Create a container
use Flashytime\Container\Container;
$container = new Container();
Register a closure
$this->container->set('hello', function () {
    return 'Hello World!';
});
echo $this->container->get('hello'); //Hello World!
$this->container->set('name', function () {
    return 'Mocha';
});
$this->container->set('mocha', function ($container) {
    return sprintf('Hello %s!', $container->get('name'));
});
echo $this->container->get('mocha'); //Hello Mocha!
Register a instance or class
$this->container->set('foo', function () {
    return new Foo();
});

or

$this->container->set('foo', new Foo());

or

$this->container->set('foo', 'Flashytime\Container\Tests\Foo');

or

$this->container->set('foo', Flashytime\Container\Tests\Foo::class);
Get the entry
$this->container->get('foo');
Register a singleton
$this->container->setSingleton('foo', Flashytime\Container\Tests\Foo::class);
$first = $this->container->get('foo');
$second = $this->container->get('foo');
var_dump($first === $second); //true
Dependency Injection
interface FooInterface
{

}

class Foo implements FooInterface
{
    private $name;
    private $age;

    public function __construct($name = null, $age = 0)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

    public function getAge()
    {
        return $this->age;
    }
}

class Bar
{
    public $foo;

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

    public function getFoo()
    {
        return $this->foo;
    }
}
$this->container->set(FooInterface::class, Foo::class);
$this->container->set('bar', Bar::class);
$bar = $this->container->get('bar');
var_dump($bar instanceof Bar); //true
var_dump($bar->getFoo() instanceof Foo); //true

see tests to get more usages.

License

MIT