Symfony2 Lazy Services 何时使用?

Symfony2 Lazy Services When to use?

我有一个关于 symfony2 惰性服务的问题。我们什么时候应该使用惰性服务,什么时候应该避免它们?如果我们使用惰性服务,会有任何开销吗?

来自documentation

In some cases, you may want to inject a service that is a bit heavy to instantiate, but is not always used inside your object. For example, imagine you have a NewsletterManager and you inject a mailer service into it. Only a few methods on your NewsletterManager actually use the mailer, but even when you don't need it, a mailer service is always instantiated in order to construct your NewsletterManager.

Configuring lazy services is one answer to this. With a lazy service, a "proxy" of the mailer service is actually injected. It looks and acts just like the mailer, except that the mailer isn't actually instantiated until you interact with the proxy in some way.

是的,有一些开销。但它是最小的。您应该避免在不需要时使用惰性服务。 (就这么简单)。

示例:

如果您的服务 A 有 3 个方法并且依赖于 B 和 C。如果您知道 B 在所有 3 个方法中使用而 C 我只在一个方法中使用,那么您 可能 考虑将 C 声明为惰性的。如果 C 是一个繁重的服务,你 应该 声明它有惰性。在此示例中,将 B 声明为惰性不会有任何好处...所以不要... =)