简体   繁体   中英

Symfony 3 - How to set Parameter before Framework loads

I am trying to solve the Cache problem in Symfony 3 by introducing version as the parameter to every asset. I am using Assetic

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

This works fine. However, the problem is that I have to edit the parameters.yml each time manually when I deploy some release to production. So I need this to be automatically generated/updated each time when a deployment happens.

One way I can think of is to generate a MD5 string based on a file's last change. So, lets say if I was able to get a version. I want to replace the parameter with the version.

Using CompilerPass , I can add the version parameter.

//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() added as a test. However, this code works and adds the parameter "version" however AFTER "framework" configuration is initialized. Due to this, %version% under "framework" block states it cannot find the parameter.

How do I create this parameter before "framework" initializes ?

There's also a way to prepend configuration before calling load() for each extension. See http://symfony.com/doc/current/components/dependency_injection/compilation.html#prepending-configuration-passed-to-the-extension

Basically, just implement PrependExtensionInterface and write prepend() method:

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

Btw, I did something similar some time ago by checking that last commit id with (If you're not using git just ignore this :)):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM