如何在服务symfony中添加配置?

时间:2017-07-24 08:52:31

标签: php symfony

我正在尝试研究如何创建自己的配置并在我的服务中实现它。我有这个配置。

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

我使用cofiguration

在我的依赖注入中成功创建了这个
private function addSampleConfiguration(ArrayNodeDefinition $node){
        $node->children()

            ->arrayNode("admin")
                ->children()
                    ->scalarNode('key')->end()
                    ->scalarNode('secret')->end()
                ->end()
            ->end()
         ->end();
    }

但在我的服务中,我想获得键值和秘密值。

class SampleService
{

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

我尝试阅读文档。但说实话,我对如何做到这一点感到困惑。我没有任何线索可以开始。

1 个答案:

答案 0 :(得分:1)

我认为您要创建自定义捆绑配置。它很好described in documentation

您需要将配置传递给您的服务 - 例如。通过构造函数注入:

class OpentokSessionService {

    private $key;
    private $secret;

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

    //… 
}

然后您需要配置服务以加载设置:

<!-- 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>

在您的扩展程序文件中:

// 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']);
}