简体   繁体   English

PHP-DI - 工厂与对象之间的差异

[英]PHP-DI - Differences between Factories and Objects

PHP-DI allows some methods to define injections, including factories and objects: http://php-di.org/doc/php-definitions.html . PHP-DI允许一些方法来定义注入,包括工厂和对象: http//php-di.org/doc/php-definitions.html

Factories : 工厂

TestClass::class => function () {
   return new TestClass('param');
}

The TestClass instance is created lazily, only when it is needed. 只有在需要时才会懒惰地创建TestClass实例。

Objects : 对象

TestClass::class => DI\object()->constructor('param')

If you use Objects, is the instance also created lazily? 如果你使用Objects,那么实例也是懒惰创建的吗?

If yes, what's the difference between factories and objects? 如果是,工厂和物体之间有什么区别?

PHP-DI author here, it seems there is some confusion (given the question and how wrong the other answer is). 这里的PHP-DI作者,似乎存在一些混淆(给出问题以及其他答案有多么错误)。 I have improved the documentation, hopefully that will clear things up: ec8120ee . 我已经改进了文档,希望能够解决这个问题: ec8120ee

To answer your questions: 回答你的问题:

If you use Objects, is the instance also created lazily? 如果你使用Objects,那么实例也是懒惰创建的吗?

Yes , all definitions are resolved lazily, object() too. 是的 ,所有定义都是懒惰地解决, object()也是如此。

If yes, what's the difference between factories and objects? 如果是,工厂和物体之间有什么区别?

Just the syntax. 只是语法。 In some cases it's more practical to write a closure, in some other cases you may want to avoid the boilerplate by using object() . 在某些情况下,编写闭包更为实际,在其他一些情况下,您可能希望通过使用object()来避免使用样板。

It's just a syntax preference honestly. 这只是一个语法偏好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM