Pimple DI integrates DI functionality with Pimple.
- Integrating DI (constructor Injection) functionality with Pimple.
- Easy to use.
Add okeyaki/pimple
to your composer.json
:
$ composer require okeyaki/pimple-di
At first, create a sub-class of Pimple\Container
and mixin Okeyaki\Pimple\DiTrait
:
class Container extends \Pimple\Container
{
use \Okeyaki\Pimple\DiTrait;
}
Then, create an instance of the class:
$container = new Container();
Pimple DI resolves dependencies automatically by the classes of constructor parameters:
class Foo
{
}
class Bar
{
private $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
public function foo()
{
return $this->foo;
}
}
$foo = $container[Foo::class];
$bar = $contaienr[Bar::class];
$bar->foo();
You can bind classes to an existing ID:
class Foo
{
}
$container['foo'] = function () {
return new Foo();
};
$container->bind(Foo::class, 'foo');
$foo = $container[Foo::class];
This is useful on using Silex proprietary or third-party providers.
You can instanciate a class and resolve its dependencies automatically:
class Foo
{
}
class Bar
{
private $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
$this->name = $name;
}
public function foo()
{
return $this->foo;
}
}
$bar = $container->make(Bar::class);
$bar->foo();
If a constructor has unresolvable parameters:
class Bar
{
private $foo;
private $baz;
public function __construct(Foo $foo, $baz)
{
$this->foo = $foo;
$this->baz = $baz;
}
public function foo()
{
return $this->foo;
}
public function baz()
{
return $this->baz;
}
}
$bar = $container->make(Bar::class, [
'baz' => 'baz',
]);
$bar->foo();
$bar->baz();
class App extends \Silex\Application
{
use \Okeyaki\Pimple\DiTrait;
}