首先,我将解释为什么我实现我的解决方案为您来决定,如果这种情况下是适合你的。
我需要一种方法来轻松地加载自定义.yml文件在我的包中(对于很多捆绑包),所以为每个文件添加一个单独的行到app/config.yml对于每个安装似乎都很麻烦。
此外,我希望大部分配置已经默认加载,所以最终用户甚至不需要担心配置大部分时间,特别是不检查每个配置文件的设置是否正确。
如果这对你来说似乎是一个类似的情况,请继续阅读。如果没有,只需使用Kris解决方案,也是一个不错的选择!
回来时,我遇到了一个需要此功能,Symfony2的didnt't提供了一种简单的方式来实现这一点,所以在这里我如何解决它:
首先,我创建了一个本地YamlFileLoader类基本上一个简单化的Symfony2一个:
<?php
namespace Acme\DemoBundle\Loader;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Config\Loader\FileLoader;
/**
* YamlFileLoader loads Yaml routing files.
*/
class YamlFileLoader extends FileLoader
{
/**
* Loads a Yaml file.
*
* @param string $file A Yaml file path
*
* @return array
*
* @throws \InvalidArgumentException When config can't be parsed
*/
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$config = Yaml::parse($path);
// empty file
if (null === $config) {
$config = array();
}
// not an array
if (!is_array($config)) {
throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $file));
}
return $config;
}
/**
* Returns true if this class supports the given resource.
*
* @param mixed $resource A resource
* @param string $type The resource type
*
* @return Boolean True if this class supports the given resource, false otherwise
*
* @api
*/
public function supports($resource, $type = null)
{
return is_string($resource) && 'yml' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'yaml' === $type);
}
}
然后我更新DIC延长我的包(它通常是自动生成的,如果你让Symfony2中创建完整的包结构,如果不只是在与弗洛捆绑软件目录下创建一个DependencyInjection/<Vendor&BundleName>Extension.php
文件翼内容:
<?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;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class AcmeDemoExtension extends Extension
{
/**
* {@inheritDoc}
*/
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');
// until here everything is default config (for your DIC services)
$ymlLoader = new YamlFileLoader(new FileLocator(__DIR__.'/../Resources/config'));
$container->setParameter('param_name', $ymlLoader->load('yaml_file_name'))); // load yml file contents as an array
}
}
现在你可以访问/传递你的yaml配置作为简单的服务参数(即, %param_name%
为services.yml)
感谢深入的回答,非常有帮助。 – 2012-01-11 10:41:16