Skip to content

Instantly share code, notes, and snippets.

@chalasr
Created February 29, 2016 22:09
Show Gist options
  • Save chalasr/362c7c62ee9d1e0e5ad0 to your computer and use it in GitHub Desktop.
Save chalasr/362c7c62ee9d1e0e5ad0 to your computer and use it in GitHub Desktop.
Load configuration files depending on host in Symfony
// src/AcmeBundle/DependencyInjection/AcmeExtension.php
<?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'));
$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 = sprintf('parameters_%s.yml', $container->getParameter('router.request_context.host'));
if (!file_exists($rootdir.'/config/'.$parameters)) {
$parameters = 'parameters.yml'; // Default
}
$paramLoader->load($parameters);
}
}
// src/AcmeBundle/DependencyInjection/Configuration.php
<?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;
}
}
@chalasr
Copy link
Author

chalasr commented Mar 2, 2016

If router.request_context.host is always equal to localhost, use $_SERVER['SERVER_NAME'] instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment