I'm writing a console app using Symfony 2 Console Component, and I want to run a console clear command before (or as) the first line of my app.
I have done some research and am struggling to find if this is possible.
I have been looking for similar functionality. There is nothing built-in to the symfony console that can clear the screen as far as I can tell, but you can still achieve the clear
behavior by using the escape code for resetting the terminal like so:
$output->write(sprintf("\033\143"));
See the post "Clear the Ubuntu bash screen for real" and "What commands can I use to reset and clear my terminal?" for a more extensive explanation of the codes, and this symfony console pull request, where I got the code from, that attempted to emulate the clear
functionality.
As the doc says, you can use something like this:
$kernel = $this->getContainer()->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(array(
'command' => 'cache:clear',
));
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
As your are using a command, your command must extends ContainerAwareCommand
so you can access the container and your services.