Load configurations from custom bundle in Symfony2
When I build apps or add new functionality to Symfony2 I build it into a separate bundle, thus trying to keep the structure modular which is generally a good practice as everyone knows. Keeping all parts of the bundle together makes it easy to maintain and also easy to change the configurations as they reside in same place as the code itself.
In this post I’ll show you how to make Symfony2 core discover your config.yml and services files defined in your custom bundle.
Create new bundle
First let’s create a new bundle that we’ll use as a demo. Run following command in the terminal:
Now you should have your bundle generated in similar path to:
Next create a directory called: DependencyInjection in the bundle directory and there create new file called DemoExtension.php. This will hold all of our code that will tell Symfony2 to load the extra config files.
Load the YAML files
The code above will load the two specified files “config.yml” and “services.yml” assuming they are in the correct directory which should be:
Handle different environments
You might be wondering what should we do if we want to have different configuration files for different environments. That could be quite handy if you have Sandbox service connection and Production service connection and you want to use one or the other based on your environment variables. That is easy all we have to do is just specify an ENV suffix in the file that we want to load:
Use config imports
There is one more option which could be easier but you have less control there. You can accomplished this by referencing it as an import in app/config.yml
Leave a Reply