I will first explain why I implemented my solution for you to decide if this case is right for you.
I needed a way to easily load custom .yml files in my bundle (for a large number of packages), so adding a separate line to app / config.yml for each file seemed like a lot of trouble for you for each installation.
In addition, I wanted most configurations to load by default already, so end users didn't even have to worry about setting up most of the time, especially not checking if each configuration file was configured correctly.
If this seems like a similar case for you, read on. If not, just use Chris's solution, that's good too!
Back when I came across the need for this feature, Symfony2 did not provide an easy way to achieve this, so this is how I solved it:
First, I created a local YamlFileLoader class, which was basically a dumbfounded Symfony2 character:
<?php namespace Acme\DemoBundle\Loader; use Symfony\Component\Yaml\Yaml; use Symfony\Component\Config\Loader\FileLoader; class YamlFileLoader extends FileLoader { public function load($file, $type = null) { $path = $this->locator->locate($file); $config = Yaml::parse($path);
Then I updated the DIC extension for my package (it is usually generated automatically if you allow Symfony2 to create a complete bundle architecture, if not just create the DependencyInjection/<Vendor&BundleName>Extension.php file in your package directory with the following content:
<?php namespace Acme\DemoBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; use Acme\DemoBundle\Loader\YamlFileLoader; class AcmeDemoExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml');
And now you can access / yaml config as a simple service parameter (i.e. %param_name% for services.yml)
Inoryy
source share