Scenario:
- I’m using the dependency-injection component as a stand-alone component. No bundles/symfony-framework and stuff.
- I have a set of services all being responsible for similar things, e.g. for writing data to the hard disk by different ways (e.g. by ftp, direct file operations, storing into a db, …)
- Each of these services requires different configuration (e.g. sql credentials, ftp credentials, …)
- I want to define one of these services as the “general service to use” for other services to have a dependency on.
- Which service to use is configured by a parameter
Example:
Given these simplified parameter and service definitions:
<parameter key="file.adapterType">direct</parameter>
<service id="file.db" />
<service id="file.ftp" />
<service id="file.direct" />
I’d like to define an alias to the service I actually want to use
<service id="file.adapter" alias="file.%file.adapterType%"/>
for other services simply relying on this service:
<service id="photos">
<argument type="service" id="file.adapter" />
</service>
What I have tried so far:
- Defining an alias with an parameter in it’s alias-id. However the parameter within the alias-id does not get resolved.
-
Defining the id directly within the argument-tag – again the parameter is not resolved her:
<service id="photo"> <argument type="service" id="file.%file.adapterType%" /> </service> -
Creating a factory. The get-method receives the parameter and the di-container and returns the corresponding service:
public function get(ContainerInterface $container, $parameter) { return $container->get('file.' . $parameter); }However the container does not register itself as a service. Registering it beforehand does not take affect when loading the configuration from a file (resulting in an error message “service ‘container’ not found”):
$container->set("container", $container); $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/services')); $loader->load('fileadapter.xml'); // << gives error $container->get("container"); // << working
Other alternatives?
I can’t set the alias after loading the configuration file as there are services within the file that have a dependency on the alias.
Anyone got other ideas on how to handle this?
Actually, I believe you were on the right track with the third bullet point in the “What I’ve tried so far” section, except that the service container does register itself as a service, but it’s called
service_container, notcontainer.