- Service locator
- Constructor injection
- Support singleton
- Standalone module/component for Rock Framework
From the Command Line:
composer require romeoz/rock-di
In your composer.json:
{
"require": {
"romeoz/rock-di": "*"
}
}
namespace test;
use rock\di\Container;
class Foo
{
}
$config = [
'class' => '\test\Foo',
// 'singleton' => true, // if you want to return singleton
];
$alias = 'foo' ; // short alias
Container::register($alias, $config);
$foo = Container::load('foo');
####Constructor injection
namespace test;
use rock\di\Container;
class Foo
{
}
class Bar
{
public $foo;
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
}
$config = [
'class' => '\test\Foo',
];
Container::register('foo' , $config);
$config = [
'class' => '\test\Bar',
];
Container::register('bar' , $config);
$bar = Container::load('bar');
$bar->foo instanceof Bar; // output: true
####Configure properties
namespace test;
use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;
class Foo implements ObjectInterface
{
use ObjectTrait;
public $name;
}
$config = [
'class' => '\test\Foo',
// properties
'name' => 'Tom'
];
Container::register('foo', $config);
$foo = Container::load('foo');
echo $foo->name; // output: Tom
Configure properties through setters and getters:
namespace test;
use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;
class Foo implements ObjectInterface
{
use ObjectTrait;
private $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$config = [
'class' => '\test\Foo',
// properties
'name' => 'Tom'
];
Container::register('foo', $config);
$foo = Container::load('foo');
echo $foo->name; // output: Tom
- PHP 5.4+
The Rock Dependency Injection is open-sourced software licensed under the MIT license.