symfony2 从控制器重新编译容器

symfony2 recompile container from controller

我想在使用 $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();
}

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

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

如果您试图获取请求期间已修改的参数值,您可以这样做:

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']
));

总之答案是否定的,容器不会重新编译,因为它已经加载到内存中,从磁盘中删除文件对当前请求没有影响。在下一次请求时,缓存将被预热,容器将在您到达控制器之前被编译。