symfony2从控制器重新编译容器

时间:2016-04-06 11:19:25

标签: symfony controller containers recompile

我想在使用$this->container->compile();

时从控制器重新编译容器
public function changeAction(Request $request)
{
    //......
    echo($this->container->getParameter('mailer_user')."\n");
    /*$cmd='php ../app/console cache:clear';
    $process=new Process($cmd);
    $process->run(function ($type, $buffer) {
        if ('err' === $type) {
            echo 'ERR > '.$buffer;
        }
        else {
            echo 'OUT > '.$buffer;
        }
    });*/

    $this->container->compile();
    echo($this->container->getParameter('mailer_user')."\n");
    die();
}

我收到错误:您无法编译转储的冷冻容器

我想知道当我从控制器清除缓存时,容器是否会重新编译?

2 个答案:

答案 0 :(得分:2)

如果您尝试获取在请求期间已修改的参数值,则可以执行以下操作:

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

public function changeAction(Request $request)
{
    $originalParam = $this->container->getParameter('mailer_user');

    // Rebuild the container
    $container = new ContainerBuilder();    
    $fileLocator = new FileLocator($this->getParameter('kernel.root_dir').'/config');

    // Load the changed config file(s)
    $loader = new PhpFileLoader($container, $fileLocator);
    $loader->setResolver(new LoaderResolver([$loader]));
    $loader->load('parameters.php'); // The file that loads your parameters

    // Get the changed parameter value
    $changedParam = $container->get('mailer_user');

    // Or reset the whole container
    $this->container = $container;
}

此外,如果您需要从控制器清除缓存,则有一种更简洁的方法:

$kernel = $this->get('kernel');
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);

$application->run(new \Symfony\Component\Console\Input\ArrayInput(
    ['command' => 'cache:clear']
));

答案 1 :(得分:0)

简而言之,答案是否定的,容器不会被重新编译,因为它已经加载到内存中,从磁盘删除文件对当前请求不起作用。并且在下一个请求时,缓存将被预热,并且在到达控制器之前将对容器进行编译。