Search code examples
phpsymfonydependency-injectionproxy-classes

Symfony2: Dependency injection reliant on request


Preamble

My Symfony2 application will be accessed from several TLD's. Depending on the TLD I want to use a different swiftmailer mailer. I however failed to dynamically inject the correct mailer despite trying a multitude of approaches (service factory, compiler pass, DI extension, "dynamic alias").

This lead to a fundamental realisation: Dependencies are injected before the container is compiled, the request is available after the container is compiled. Hence there is no way to make dependency injection reliant on the request (and therefore all above-mentioned approaches failed).

Problem

I was told never to pull dependencies, but to always inject them.

To illustrate this further:

I have

  • three swiftmailers: mailer_en, mailer_de, mailer_ie and
  • three domains: domain.co.uk, domain.de and domain.ie

and want to inject the correct swiftmailer into a custom mailer service for FOSUserBundle (or into any other service that needs swiftmailer).

Question

How do I inject the correct dependency if I don't know it until the request is available?

I had two ideas, but not sure as to how suitable they are:

  1. Should I inject some kind of "Mailer Provider"? Still kind of pulling dependencies, isn't it?
  2. Can I use some kind of proxy class, forwarding interaction to the correct emailer?

Or am I completely on the wrong route?


Solution

  • Injecting the request is covered in the documentation. That being said, I think you'll get the most bang for the buck by using a factory.