gpt4 book ai didi

php - Symfony2 Lazy Services 何时使用?

转载 作者:可可西里 更新时间:2023-11-01 13:24:14 25 4
gpt4 key购买 nike

我有一个关于 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 声明为惰性不会有任何好处...所以不要... =)

关于php - Symfony2 Lazy Services 何时使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com