[英]Call KernelInterface in Symfony Controller
I need to run some Symfony commands from controller in order server are not support ssh connection.我需要从控制器运行一些 Symfony 命令,以便服务器不支持 ssh 连接。
I found this Symfony docs https://symfony.com/doc/3.3/console/command_in_controller.html我找到了这个 Symfony 文档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.这段代码几乎就像 Symfony 文档中的一个例子。
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\\Component\\HttpKernel\\KernelInterface”是一个接口,不能被实例化
Symfony version is 3.3 Symfony 版本是 3.3
PHP version is 7.1 PHP 版本是 7.1
I must add that I am using FOSRest bundle, but I guess that should not be a problem.我必须补充一点,我正在使用 FOSrest 包,但我想这应该不是问题。
What I do wrong here?我在这里做错了什么? Am I missing something?我错过了什么吗?
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);
}
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.我此时仍在运行 3.4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.