我在使用
ContainerBuilder
配置容器时设置了依赖项和定义,然后编译它以获得实际的 Container
,但每当我尝试注入依赖项时,它们总是会被忽略。
我是否错过了
injectOn()
方法的概念,或者我在这里做错了什么($this->translator
仍未分配)?我尝试了不同的方法,既实例化类并将对象添加到 ContainerBuilder
中,又将其作为 \DI\object()
定义传递,两者都具有相同的结果。
<?php
include "../vendor/autoload.php";
class Translator
{}
class TextHandle
{
protected $translator;
public function setTranslator (Translator $translator)
{
$this->translator = $translator;
}
public function test ()
{
var_dump($this->translator);
}
}
class TestCase
{
protected $translator;
public function __construct (Translator $translator)
{
$this->translator = $translator;
}
}
// Setup container
$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->addDefinitions([
Translator::class => \DI\object(),
]);
$container = $containerBuilder->build();
// Create object and inject
$textHandle = new TextHandle();
$container->injectOn($textHandle);
// Test injection, fails
$textHandle->test(); // NULL
// Test access, works
$translator = $container->get(Translator::class);
var_dump($translator); // object(Translator)#18 (0) {}
// Try having the container instantiate
$textHandle = $container->make(TextHandle::class);
$textHandle->test(); // Null
// Try object with constructor, works
$testCase = $container->make(TestCase::class);
var_dump($testCase); // Translator is set
根据文档,PHP-DI 不通过setter 执行自动装配。
您应该添加
TextHandle
类的定义,并将其配置为通过 setter 注入 Translator
:
$containerBuilder->addDefinitions([
TextHandle::class => \DI\object()->method('setTranslator', \DI\get(Translator::class))
]);
如果您使用 PHP 7.4、PHP DI 6.x
事实上,您可以使用属性注入或 Setter 注入来注入依赖项
$container->injectOn($object)
这是详细信息。
$builder->useAnnotation(true)
composer require doctrine/annotations:^1.14
/**
* @Inject
*/
private NotificationServicesInterface $notificationServices;
与/或
private NotificationServicesInterface $notificationServices;
/**
* @Inject
*/
public function setNotificationServices(NotificationServicesInterface $notificationServices) {
$this->notificationServices = $notificationServices;
}
注:
make()
或call()
。仅在必要时才使用 injectOn()
。#[Inject]
private NotificationServicesInterface $notificationServices;