I'm trying to empty the Symfony 2 cache through my application just as if I was doing php app/console cache:clear
.
I've tried many different solutions, such as:
//solution 1
$process = new Process('php '.__DIR__.'/../../../../../app/console cache:clear');
$process->setTimeout(3600);
$process->run();
//solution 2
$input = new StringInput(null);
$output = new NullConfigurationOutput();
$command = new CacheClearCommand();
$command->setContainer($container);
$command->run($input, $output);
//solution 3
$container->get('cache_clearer')->clear($container->getParameter('kernel.cache_dir'));
I've also tried to rm -Rf
the cache folder.
None of them is fully working as i'm getting many errors. The following error is the one i'm getting on solution 2 (which seemed to be the best):
Failed to start the session: already started by PHP ($_SESSION is set).
Seems like Symfony is trying to rebuild the page or reboot the application during the render process.
How could someone clear the cache via some php code?
EDIT : I'm actually trying to regenerate the cache because of my routing system. I've made a bundle which take a symfony 2 route and add the possibility to rewrite it for SEO purpose (example : i have a front_category route which point to /category, with this bundle i can rewrite it to category-seo-optimized.html).
If i'm on a route which needs particular parameter, such as an ID, i need to make a special route for it in order to rewrite it. For example, for /category/3 i need to create a route which is named category_3 and.. in order to let symfony knows i've changed the routing system, i had to clear the cache.
A similar question is already answered here: Symfony 2.4 execute Command from Controller - answered Mar 20 at 15:37 pomaxa.
I've tested and extended pomaxa's code:
Controller code
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
$command = $this->container->get('yourservice.cache.clear');
//$dynamicEnvMode = $this->container->getParameter('kernel.environment')
$staticEnvMode = 'dev'; // to use develop mode
$staticEnvMode = 'prod --no-debug'; // to use production mode
$input = new ArgvInput(array('--env=' . $staticEnvMode ));
$output = new ConsoleOutput();
$command->run($input, $output);
I used static environment mode and I tried to use CacheClearCommand object instead of service, but it haven't worked. Cache clear operation can use long time to load, so using a service might do it better.
Best way would be solve your problem without cache clear. Find the fast changing entities,actions or anything you need, and disable caching for them. If you post a detailed question (and put the link in comment) from, why you need ignore cache and where, then I could help you to find an other way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With