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

前端之家收集整理的这篇文章主要介绍了php – Symfony 2 – 如何在我自己的Yaml文件加载器中解析%parameter%?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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%

目前,结果数组包含’hostname’数组键的’%profiles.germany.host_name%’.

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

我一直在浏览Symfony 2代码和文档(和this SO question并且无法在框架内找到这样做的地方.我可以编写自己的参数解析器 – 从内核中获取参数,搜索%foo %字符串和查找/替换…但如果有一个组件准备使用,我更喜欢使用它.

为了给出更多背景知识,为什么我不能将它包含在主config.yml中:我希望能够加载app / config / profiles / *.yml,其中*是配置文件名称,我正在使用我自己的Loader来实现这一目标.如果有一种通配符导入配置文件方法,那么这对我也有用.

注意:目前正在使用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的依赖注入组件使用编译器传递来在优化阶段解析参数引用.

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

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

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

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

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

我意识到这是一个古老的问题,但我已经花了很长时间来为我自己的项目搞清楚这一点,所以我在这里发布答案以供将来参考.

原文链接:https://www.f2er.com/php/136633.html

猜你在找的PHP相关文章