我试图熟悉Dice依赖注入,但是第一次尝试却失败了。
我想告诉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
如果要运行代码,则需要使用来配置composer "require": {"tombzombie/dice": "dev-master"}
。
规则必须获取我要实例化的类的名称,如示例代码所示
但是,除非我也为添加了相同的规则MyOtherClass
,否则仍然不能在全球范围内使用此替换,但是这不会像我期望的那样在全球范围内使用。
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('*', $rule);
$instance = $dice->create("Example\\MyClass");
$instance = $dice->create("Example\\MyOtherClass");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句