Symfony 3 -如何在框架加载前设置参数


Symfony 3 - How to set Parameter before Framework loads

我试图通过引入版本作为每个资产的参数来解决Symfony 3中的缓存问题。我用的是astic

# app/config/config.yml
parameters:
    version: 'v1.0'
framework:
    # ...
    assets:
        version: '%version%'

这很好。然而,问题是,当我将一些版本部署到生产环境时,我每次都必须手动编辑parameters.yml。因此,我需要在每次部署发生时自动生成/更新此文件。

我能想到的一种方法是基于文件的最后更改生成MD5字符串。假设我能得到一个版本。我想用版本替换参数。

使用CompilerPass,我可以添加version参数。

//AppBundle/AppBundle.php
use AppBundle'DependencyInjection'Compiler'Version;
class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container); // TODO: Change the autogenerated stub
        $container->addCompilerPass(new Version());
    }    
}


//AppBundle/DependencyInjection/Compiler/Version.php
namespace AppBundle'DependencyInjection'Compiler;

use Symfony'Component'DependencyInjection'Compiler'CompilerPassInterface;
use Symfony'Component'DependencyInjection'ContainerBuilder;
class Version implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container->setParameter('version', uniqid());
    }
}

添加uniqid()作为测试。然而,这段代码可以工作,并且在初始化"框架"配置之后添加参数"版本"。因此,%version%在"framework"块下声明它找不到参数。

如何在"framework"初始化之前创建这个参数?

还有一种方法可以在为每个扩展调用load()之前预先添加配置。看到http://symfony.com/doc/current/components/dependency_injection/compilation.html prepending-configuration-passed-to-the-extension

基本上,只需实现PrependExtensionInterface并编写prepend()方法:

public function prepend(ContainerBuilder $container)
{
    // ...
}

顺便说一句,我以前做过类似的事情,通过检查最后一次提交id(如果你不使用git就忽略这个:)):

git log --pretty=oneline -1 --format="%H"