A lightweight PHP dependency injection container.
composer require flashytime/container
use Flashytime\Container\Container;
$container = new Container();
$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!
$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);
$this->container->get('foo');
$this->container->setSingleton('foo', Flashytime\Container\Tests\Foo::class);
$first = $this->container->get('foo');
$second = $this->container->get('foo');
var_dump($first === $second); //true
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.