okeyaki / pimple-di
This package is abandoned and no longer maintained.
No replacement package was suggested.
Integrates DI functionality with Pimple.
1.0.1
2017-12-20 04:39 UTC
Requires
- pimple/pimple: ^2.0|^3.0
Requires (Dev)
- symfony/phpunit-bridge: ^3.2
This package is not auto-updated.
Last update: 2020-01-24 16:41:54 UTC
README
Pimple DI integrates DI functionality with Pimple.
Features
- Integrating DI (constructor Injection) functionality with Pimple.
- Easy to use.
Installation
Add okeyaki/pimple
to your composer.json
:
$ composer require okeyaki/pimple-di
Usage
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();
Constructor Injection
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();
Class Binding
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.
Instanciation
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();
Examples
Integrating with Silex
class App extends \Silex\Application
{
use \Okeyaki\Pimple\DiTrait;
}