Reputation: 7199
I need to run some Symfony commands from controller in order server are not support ssh connection.
I found this Symfony docs https://symfony.com/doc/3.3/console/command_in_controller.html
/**
* @Route("/command/run")
* @Method("POST")
*
* @param KernelInterface $kernel
*
* @return Response
* @throws \Exception
*/
public function runCommandAction(KernelInterface $kernel)
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'doctrine:schema:update',
"--force" => true
]);
$output = new BufferedOutput();
$application->run($input, $output);
$content = $output->fetch();
return new Response($content);
}
This code is almost like an example from Symfony docs.
But I get this error when the code is run.
The provided type "Symfony\Component\HttpKernel\KernelInterface" is an interface, and can not be instantiated
Symfony version is 3.3
PHP version is 7.1
I must add that I am using FOSRest bundle, but I guess that should not be a problem.
What I do wrong here? Am I missing something?
Upvotes: 0
Views: 1773
Reputation: 1772
I think the easiest way to get the kernel in a controller is like this.
$this->get('kernel')
So instead of adding the kernel to the controller object as a private member variable like this.
$application = new Application($this->kernel);
I do this.
$application = new Application($this->get('kernel'));
I'm still running 3.4 at this time.
Upvotes: 1
Reputation: 7199
I had solved this issue by adding interface in construct class.
/**
* @var KernelInterface
*/
private $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* @Route("/command/run")
* @Method("POST")
*
* @param KernelInterface $kernel
*
* @return Response
* @throws \Exception
*/
public function runCommandAction()
{
$application = new Application($this->kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'doctrine:schema:update',
"--force" => true
]);
$output = new BufferedOutput();
$application->run($input, $output);
$content = $output->fetch();
return new Response($content);
}
Upvotes: 1