Symfony上的动态数据库参数文件

时间:2017-01-04 16:14:15

标签: symfony

我是Symfony的新手,我试图加载不同的parameters.yml,具体取决于主机,包括数据库配置。所以,在apache vhosts中,我定义了一个变量,通过$ _SERVER [" CLIENTID"](Directive SetEnv)让我知道PHP中的客户端是什么。现在我想,例如,如果CLIENTID是" client1",加载parameters_client1.yml,包含db_host,db_user等... 我试过这种方式:

应用程序/配置/ config.yml

doctrine:
    dbal:
        host:     "%db_host%"
        dbname:   "%db_name%"
        user:     "%db_user%"
        password: "%db_password%"

应用程序/配置/ parameters_client1.yml

parameters:
    db_host: "localhost"
    db_name: "client1_database"
    db_user: "client1"
    db_password: "something"

的src /的appbundle / DependencyInjection /的configuration.php

namespace AppBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('appbundle');
        return $treeBuilder;
    }
}

的src /的appbundle / DependencyInjection / AppExtension.php

namespace AppBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class AppExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        $rootdir = $container->getParameter('kernel.root_dir');
        // Load the bundle's services.yml
        $loader = new Loader\YamlFileLoader($container, new         FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
        // Load parameters depending on current host
        $paramLoader = new Loader\YamlFileLoader($container, new FileLocator($rootdir.'/config')); // Access the root config directory

        $parameters = "parameters.yml";

        if( array_key_exists("CLIENTID", $_SERVER) )
        {
            $paramfile = sprintf('parameters_%s.yml', $_SERVER["CLIENTID"]);
            if (file_exists($rootdir.'/config/'.$paramfile))
            {
                $parameters = $paramfile;
            }
        }

        $paramLoader->load($parameters);
    }
}

但那不起作用,我收到了以下错误:

ParameterNotFoundException in ParameterBag.php line 100:
You have requested a non-existent parameter "db_host".

有人可以解释一下我错过了什么吗? 我正在使用Symfony 3.2

1 个答案:

答案 0 :(得分:1)

粗略猜测你在app / config / config.yml

中包含资源
imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }