在命令中使用控制器作为服务
Use a controller as a service in a command
我正在尝试通过 Symfony 命令使用 Wkhtmltopdf。
我决定使用 KnpSnappyBundle,所以我创建了一个用作服务的控制器。
WkhtmltopdfController.php
class WkhtmltopdfController extends Controller {
public function indexUrl()
{
$snappy = $this->get('knp_snappy.pdf');
$filename = 'myFirstSnappyPDF';
$url = 'http://ourcodeworld.com';
return new Response(
$snappy->getOutput($url),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}}
然后我像这样从我的 Command 构造函数中导入这个服务。
我的命令
class GenerateQuittance extends Command {
private $snappy;
private $container;
public function __construct(WkhtmltopdfController $knpSnappyPdf, ContainerInterface $container)
{
parent::__construct();
$this->snappy = $knpSnappyPdf;
$this->container = $container;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
[...]
$this->snappy->indexUrl();
}
但我收到 [错误] 运行 命令 "app:myCommand" 时抛出的错误。消息:"Call to a member function get() on null".
那么我如何将 WkhtmltopdfController 中的方法用于命令。
谢谢,
将控制器作为服务注入通常是个坏主意,因为它们从 Symfony 得到特殊处理。考虑将您的 WkhtmltopdfController::indexUrl()
方法重构为单独的服务。您可能还想将 $filename
变量转换为参数并将方法的 return 值转换为普通输出而不是 Response
。
另请注意,注入 ContainerInterface
也被认为是一种不良做法,您需要明确列出要注入的服务。
您的特定错误很可能是由于 get()
方法由 ContainerTrait
提供,期望 ContainerInterface
可用(通过在基础容器中使用 ContainerAwareTrait
), 但这种注入可能不会发生在控制台 Application
.
的情况下
我正在尝试通过 Symfony 命令使用 Wkhtmltopdf。
我决定使用 KnpSnappyBundle,所以我创建了一个用作服务的控制器。
WkhtmltopdfController.php
class WkhtmltopdfController extends Controller {
public function indexUrl()
{
$snappy = $this->get('knp_snappy.pdf');
$filename = 'myFirstSnappyPDF';
$url = 'http://ourcodeworld.com';
return new Response(
$snappy->getOutput($url),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}}
然后我像这样从我的 Command 构造函数中导入这个服务。
我的命令
class GenerateQuittance extends Command {
private $snappy;
private $container;
public function __construct(WkhtmltopdfController $knpSnappyPdf, ContainerInterface $container)
{
parent::__construct();
$this->snappy = $knpSnappyPdf;
$this->container = $container;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
[...]
$this->snappy->indexUrl();
}
但我收到 [错误] 运行 命令 "app:myCommand" 时抛出的错误。消息:"Call to a member function get() on null".
那么我如何将 WkhtmltopdfController 中的方法用于命令。
谢谢,
将控制器作为服务注入通常是个坏主意,因为它们从 Symfony 得到特殊处理。考虑将您的 WkhtmltopdfController::indexUrl()
方法重构为单独的服务。您可能还想将 $filename
变量转换为参数并将方法的 return 值转换为普通输出而不是 Response
。
另请注意,注入 ContainerInterface
也被认为是一种不良做法,您需要明确列出要注入的服务。
您的特定错误很可能是由于 get()
方法由 ContainerTrait
提供,期望 ContainerInterface
可用(通过在基础容器中使用 ContainerAwareTrait
), 但这种注入可能不会发生在控制台 Application
.