Question

Let's imagine that I have a service that can invoke other services depending on method that is called:

class Foobar
{
    public function foo() {
        return *SERVICE_A*->baz();
    }

    public function bar() {
        return *SERVICE_B*->qux();
    }
}

Now when I call foo() method of Foobar, I need to make the SERVICE_A available for Foobar. I can do it by either defining SERVICE_A and SERVICE_B as dependencies of Foobar and delegate their creation to service container at constructing stage, injecting them from the outside using setters like setServiceA() or setServiceB() methods of Foobar, or passing the service container to Foobar to make it able to construct only services that are really needed at the moment.

The first option doesn't seem right for me because it would create both SERVICE_A and SERVICE_B even if one of them won't be called. The second option is obviously wrong because it exposes the service infrastructure to the outer world. The third option is not good too since it makes the service depend on whole service container that makes code hard to test etc.

So my question is, Is there a way to lazy load service dependencies?

Était-ce utile?

La solution

Lazy Services are exactly what you're looking for.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top