user3818576
user3818576

Reputation: 3391

How to add config in service symfony?

I'm trying to study on how to create my own config and implement it in my services. I have this config.

sample_helper:
  admin:
    key: '45912565'
    secret: '2e6b9cd8a8cfe01418cassda3reseebafef9caaad0a7'

I successfully created this in my dependency injection using the cofiguration

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 the key value and secret value.

class SampleService
{

    public function generateSample(){
       $key = ''; // key here from config
       $secret = ''; //secret from config;
    }
}

I try to read the documentation. but honestly I'm confuse on how to do it. I don't have any clue to begin.

Upvotes: 3

Views: 1098

Answers (1)

jkucharovic
jkucharovic

Reputation: 4244

I presume you want to create custom bundle configuration. It's nicely described in documentation.

You need to pass configuration to your service – eg. by contructor injection:

class OpentokSessionService {

    private $key;
    private $secret;

    public function __constructor($key, $secret)
    {
        $this->key = $key;
        $this->secret = $secret;
    }

    //… 
}

Then you need to configure service to load 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 your 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']);
}

Upvotes: 1

Related Questions