【问题标题】:Symfony 3 - How to set Parameter before Framework loadsSymfony 3 - 如何在框架加载之前设置参数
【发布时间】:2016-11-15 21:39:57
【问题描述】:

我试图通过引入version 作为每个资产的参数来解决 Symfony 3 中的缓存问题。我正在使用Assetic

# 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% 表示它找不到参数。

如何在“框架”初始化之前创建这个参数?

【问题讨论】:

    标签: php dependency-injection symfony


    【解决方案1】:

    还有一种方法可以在为每个扩展调用 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      相关资源
      最近更新 更多