Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 recompile container from controller

I want to recompile container from controller when I use $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();
}

I got an error : You cannot compile a dumped frozen container

I want to know if when I clear the cache from controller the container will recompile?

like image 645
ghaziksibi Avatar asked Sep 11 '26 11:09

ghaziksibi


1 Answers

If you are trying to get values of parameters that have been modified during request, you can do this:

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;
}

Also, if you need to clear the cache from a controller, there is a cleaner way:

$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']
));
like image 91
chalasr Avatar answered Sep 14 '26 17:09

chalasr