I would like to know if it is possible to inject service’s parameters in my own service and if yes, how?
Let me put you in context. I’m using the FOSFacebookBundle which loads some configuration from the config.yml file. Those configuration settings (like my facebook app_id, secret, cookie, etc.) are kept has parameters by the FOSFacebookBundle with this code:
// FOS\FacebookBundle\DependencyInjection\FOSFacebookExtension.php
foreach (array('file', 'app_id', 'secret', 'cookie', 'domain', 'logging', 'culture', 'permissions') as $attribute) {
$containerBuilder->setParameter('fos_facebook.'.$attribute, $config[$attribute]);
}
I know it is possible to retrieve those parameters via the $container by doing:
$container->getParameter('fos_facebook.app_id');
But I would like to know if it is possible to inject those parameters directly into one of my service definition. I have one service called FacebookHelper which would need this information. So I would like to do something like:
acme.helper.facebook:
class: Application\AcmeBundle\Helper\FacebookHelper
arguments:
entityManager: "@doctrine.orm.entity_manager"
facebook: "@fos_facebook.api"
facebookAttributes:
- "@fos_facebook.app_id"
- "@fos_facebook.secret"
- "@fos_facebook.cookie"
Of course, this syntax doesn’t work because Symfony is looking for a service named fos_facebook.app_id which doesn’t exist.
I’m looking for a solution that would avoid to inject the container directly in my service. Either by doing a direct definition in my services.yml file, or via the DI extension of my bundle which would do some work to define my custom service, retrieve the parameters from FOSFacebookBundle and inject them in it.
Regards,
Matt
In fact, it is really easy and I feel ashamed that I didn’t think about it before posting my question. I knew about how to use parameters in the
config.ymlfile (i.e. by using %locale% for example) but I didn’t think about using this syntax to inject parameters in my service definition.Here is how I injected
FOSFacebookBundleparameters in my service:So simple 🙂
Hope this will help someone else.
Regards,
Matt