祖先对象中的 ZF2 依赖注入
我的目标是使用 setter 在祖先对象中使用 DI,这样我就有了祖先对象的通用 DI。例如,我的其他模型继承的抽象模型类,预先配置了实体管理器等。
到目前为止,在配置祖先并使用 DI 成功创建它之后,将其更改为抽象类,然后实例化该类的祖先 DI Abstract(无论是否设置为 Abstract)不运行。
<代码> namespace Stuki;
use Doctrine\ORM\EntityManager;
# abstract
class Model {
protected $em;
public function setEm(EntityManager $em) {
$this->em = $em;
}
}
此类的 DI
'迪' => array(
'instance' => array(
'Stuki\Model' => array(
'parameters' => array(
'em' => 'doctrine_em'
)
),
上面的类和 DI 可以工作。但我希望它在祖先对象上运行,所以
namespace Stuki\Model;
use Stuki\Model as StukiModel;
class Authentication extends StukiModel {
public function getIdentity() {
return 'ħ'; #die('get identity');
}
}
$auth = $e->getTarget()->getLocator()->get('Stuki\Model\Authentication');
最后一行 $auth = 不运行 DI。
如何在不使用内省的情况下为祖先对象设置 DI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抱歉,当我通过 Meetup 回复时,我的假设不正确;)
您问题的关键是您正在配置 Stuki\Model 以在 InstanceManager 中获取 EntityManager,但要求 Di 提供 Stuki\Authentication。
您可以切换到构造函数注入...这可行,但我真的不喜欢在祖先类中定义构造函数:
需要注意的一件事是,在我们的两个示例中,Di 仍然需要使用内省来发现实例化器、方法等内容和方法参数。避免运行时自省的唯一方法是预编译: http://packages.zendframework.com/docs/latest/manual/en/zend.di.definition.html#zend.di.definition.compilerdefinition。
Sorry my assumptions were incorrect when I replied via Meetup ;)
The crux of your problem is you are configuring Stuki\Model to take an EntityManager in the InstanceManager, but asking Di for a Stuki\Authentication.
You can switch to constructor injections...this works but I don't really like having to define constructor in ancestor class:
One thing to note, in both our examples, Di still needs to use introspection to discover things like the instantiator, methods, and method params. The only way to avoid introspection at runtime is to precompile: http://packages.zendframework.com/docs/latest/manual/en/zend.di.definition.html#zend.di.definition.compilerdefinition.