How to add config to Symfony service?
I am trying to learn how to create my own config and implement it in my services. I have this configuration.
sample_helper:
admin:
key: '45912565'
secret: '2e6b9cd8a8cfe01418cassda3reseebafef9caaad0a7'
I have successfully created this in my dependency injection using config
private function addSampleConfiguration(ArrayNodeDefinition $node){
$node->children()
->arrayNode("admin")
->children()
->scalarNode('key')->end()
->scalarNode('secret')->end()
->end()
->end()
->end();
}
but in my services i want to get key value and secret value.
class SampleService
{
public function generateSample(){
$key = ''; // key here from config
$secret = ''; //secret from config;
}
}
I am trying to read the documentation. but to be honest i am confused how to do it. I have no clue to start.
+3
source to share
1 answer
I am assuming that you want to create a custom package configuration. It's nicely described in the documentation .
You need to pass the configuration to your service - eg. by constructor injection:
class OpentokSessionService {
private $key;
private $secret;
public function __constructor($key, $secret)
{
$this->key = $key;
$this->secret = $secret;
}
//…
}
Then you need to configure the service to load the settings:
<!-- src/Acme/SomeHelperBundle/Resources/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="sample_helper.class" class="Acme\SomeHelperBundle\Service\OpentokSessionService">
<argument></argument> <!-- will be filled in with key dynamically -->
<argument></argument> <!-- will be filled in with secret dynamically -->
</service>
</services>
</container>
And in the extension file:
// src/Acme/SomeHelperBundle/DependencyInjection/SomeHelperExtension.php
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
$loader->load('services.xml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$def = $container->getDefinition('sample_helper.class');
$def->replaceArgument(0, $config['admin']['key']);
$def->replaceArgument(1, $config['admin']['secret']);
}
+1
source to share