骰子依赖注射的全球共享替代

时间:2015-05-20 15:46:27

标签: php dependency-injection

我试图熟悉骰子依赖注射,但我的第一次试验失败了。

我想告诉Dice,每个依赖于MyInterface的班级都应该获得MyInterfaceImpl的实例,因此我会使用MyClass对此进行评估。

显然,我在Dice中缺少一些细节。

这是我的示例代码:

<?php
namespace Example;

require("vendor/autoload.php");

interface MyInterface {}

class MyInterfaceImpl implements MyInterface {}

class MyClass {
    public function __construct(MyInterface $i) {}
}

class MyOtherClass {
    public function __construct(MyInterface $i) {}
}

$dice = new \Dice\Dice();

$rule = new \Dice\Rule();
$rule->shared = true;
$rule->substitutions['Example\\MyInterface'] = new \Dice\Instance('Example\\MyInterfaceImpl');
$dice->addRule('Example\\MyClass', $rule);

$instance = $dice->create("Example\\MyClass");
$instance = $dice->create("Example\\MyOtherClass");

运行此代码的输出是:

PHP Fatal error:  Cannot instantiate interface Example\MyInterface in …/vendor/tombzombie/dice/Dice.php on line 38
PHP Stack trace:
PHP   1. {main}() …/dicetest.php:0
PHP   2. Dice\Dice->create() …/dicetest.php:26
PHP   3. Dice\Dice->Dice\{closure}() …/vendor/tombzombie/dice/Dice.php:43
PHP   4. Dice\Dice->Dice\{closure}() …/vendor/tombzombie/dice/Dice.php:38
PHP   5. Dice\Dice->create() …/vendor/tombzombie/dice/Dice.php:70
PHP   6. Dice\Dice->Dice\{closure}() …/vendor/tombzombie/dice/Dice.php:43

如果您想运行代码,则需要使用"require": {"tombzombie/dice": "dev-master"}配置编辑器。

规则必须获取我想要实例化的类的名称,如示例代码

中所示

但我仍然无法在全球范围内使用此替换,除非我也为MyOtherClass添加了相同的规则,但这不是全局,因为我期待它

1 个答案:

答案 0 :(得分:1)

骰子提供default rule来定义例如如果任何类被实例化,则使用替换。它用星号*表示:

<?php
namespace Example;

require("vendor/autoload.php");

interface MyInterface {}

class MyInterfaceImpl implements MyInterface {}

class MyClass {
    public function __construct(MyInterface $i) {}
}

class MyOtherClass {
    public function __construct(MyInterface $i) {}
}

$dice = new \Dice\Dice();

$rule = new \Dice\Rule();
$rule->shared = true;
$rule->substitutions['Example\\MyInterface'] = new \Dice\Instance('Example\\MyInterfaceImpl');
$dice->addRule('*', $rule);

$instance = $dice->create("Example\\MyClass");
$instance = $dice->create("Example\\MyOtherClass");