简体   繁体   中英

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 .

Factories :

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

The TestClass instance is created lazily, only when it is needed.

Objects :

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

If you use Objects, is the instance also created lazily?

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). I have improved the documentation, hopefully that will clear things up: ec8120ee .

To answer your questions:

If you use Objects, is the instance also created lazily?

Yes , all definitions are resolved lazily, object() too.

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() .

It's just a syntax preference honestly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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