rakete rakete - 1 year ago 110
PHP Question

Symfony2: Load config-files depending on domain

At the moment we are running an online-shop for germany. Now we want also offer our products in UK with an own domain.

Depending on the domain their are several settings which should be loaded:

  • Google Analytics ID

  • Payment API Secrets/Keys, ...

  • Currency

  • Language

  • Admin Mail

  • Tracking Pixel (FB)

  • and more....

In a previous project we solved it by putting this settings in a domain-table in the database. But I think with the whole payment service information and key and and and.. it is not the best solution.

Answer Source

You can write a bundle Extension class to load your configuration depending on the host.

The bundle Extension:

// src/AcmeBundle/DependencyInjection/AcmeExtension.php


namespace AcmeBundle\DependencyInjection;

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

class AcmeExtension 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'));

        // Load parameters depending on current host
        $paramLoader = new Loader\YamlFileLoader($container, new FileLocator($rootdir.'/config')); // Access the root config directory
        $parameters = sprintf('parameters_%s.yml', $container->getParameter('router.request_context.host'));

        if (!file_exists($rootdir.'/config/'.$parameters)) {
            $parameters = 'parameters.yml'; // Default


The corresponding bundle Configuration:

// src/AcmeBundle/DependencyInjection/Configuration.php


namespace AcmeBundle\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('acme');

        return $treeBuilder;

Like this, you can create a file named parameters_localhost.yml and it will be automatically loaded. If the file is not found, the default parameters.yml will be used.

You can apply this logic based on every parameters you want (like _locale used for your translations, I guess).

Hope this help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download