php - Symfony 2 - 如何在我自己的 Yaml 文件加载器中解析 %parameter%?

标签 php symfony

我有一个 Yaml 加载器,它可以为一个“配置文件”加载额外的配置项(其中一个应用程序可以使用不同的配置文件,例如同一站点的不同本地版本)。

我的加载器非常简单:

# YamlProfileLoader.php

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Yaml\Yaml;

class YamlProfileLoader extends FileLoader
{
    public function load($resource, $type = null)
    {
        $configValues = Yaml::parse($resource);
        return $configValues;
    }

    public function supports($resource, $type = null)
    {
        return is_string($resource) && 'yml' === pathinfo(
            $resource,
            PATHINFO_EXTENSION
        );
    }
}

加载器大致是这样使用的(简化了一点,因为也有缓存):

$loaderResolver = new LoaderResolver(array(new YamlProfileLoader($locator)));
$delegatingLoader = new DelegatingLoader($loaderResolver);

foreach ($yamlProfileFiles as $yamlProfileFile) {
    $profileName = basename($yamlProfileFile, '.yml');
    $profiles[$profileName] = $delegatingLoader->load($yamlProfileFile);
}

它正在解析的 Yaml 文件也是如此:

# profiles/germany.yml

locale: de_DE
hostname: %profiles.germany.host_name%

目前,生成的数组包含 '%profiles.germany.host_name%' 作为 'hostname' 数组键。

那么,如何解析%参数来获取实际的参数值呢?

我一直在浏览 Symfony 2 代码和文档(和 this SO question,但找不到在框架本身内完成的位置。我可能会编写自己的参数解析器 - 从内核获取参数,搜索 %foo% 字符串并查找/替换...但如果有组件可供使用,我更喜欢使用它。

为了提供更多背景知识,为什么我不能将它包含到主 config.yml 中:我希望能够加载 app/config/profiles/*.yml,其中* 是配置文件名称,我使用自己的加载程序来完成此操作。如果有通配符导入配置文件的方法,那么它可能对我也有用。

注意:目前使用 2.4,但如果有帮助,即将准备升级到 2.5。

最佳答案

I've been trawling through the Symfony 2 code and docs (and this SO question and can't find where this is done within the framework itself.

Symfony 的依赖注入(inject)组件在优化阶段使用编译器传递来解析参数引用。

Compiler从其 PassConfig 获取已注册的编译器传递实例。此类配置 a few compiler passes by default ,其中包括 ResolveParameterPlaceHoldersPass .

在容器编译期间,ResolveParameterPlaceHoldersPass 使用容器的 ParameterBagresolve strings包含 %parameters%。编译器传递然后将已解析的值设置回容器。

So, how can I parse the % parameters to get the actual parameter values?

您需要访问 ProfileLoader 中的容器(或您认为合适的任何地方)。使用容器,您可以递归迭代解析的 yaml 配置并将值传递给容器的参数包,以通过 resolveValue() 解析。方法。


在我看来,也许更简洁的方法是让您在捆绑配置中实现它。这样你的配置将根据定义的结构进行验证,这可以及早发现配置错误。请参阅 bundle configuration 上的文档了解更多信息(该链接适用于 v2.7,但希望也适用于您的版本)。

我意识到这是一个老问题,但我已经花了很长时间为我自己的项目弄清楚这个问题,所以我把答案贴在这里以供将来引用。

关于php - Symfony 2 - 如何在我自己的 Yaml 文件加载器中解析 %parameter%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24675830/

相关文章:

php - Excel 下载卡住 188kb

php - 未捕获的异常 'Exception',堆栈跟踪 : #0. 中的消息 '0' PHP Insert based on API response

php - 使用 php 数组生成单个 MySQL INSERT 查询

php - FOSUserBundle 和 Symfony 3.0?

jquery-ui - Symfony 2.0日期时间小部件;如何使用JQuery UI日期选择器呈现?

php - 移除删除复选框 Sonata Admin Bundle

php - Symfony 多对多连接

php - Symfony2+学说 : How to convert iso8859-1 to utf-8 and viceversa?

php - 通过 php 的定界符本身拆分字符串

php - 是否可能返回类似 Excel 的查询?