【发布时间】:2016-03-24 10:15:49
【问题描述】:
我想在我创建的自定义类中使用 $this->container->get。 我已经阅读并发现我应该在构造函数中使用 ContainerInterface,我这样做了,但我仍然收到此错误:
错误:在非对象上调用成员函数 get()
代码如下:
MyClass.php
namespace path\to\MyClass;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyClass {
private $container;
public $user_id;
public function __contruct(ContainerInterface $container) {
$this->container = $container;
$this->user_id = $user_id;
return $this;
}
/**
* @param string $data Some data
* @return array A response
*/
public function generatePDF($data)
{
// Create the folders if needed
$pdf_folder = __DIR__.'/../../../../web/pdf/'.$this->user_id.'/';
if(!file_exists($pdf_folder))
mkdir($pdf_folder, 0755, TRUE);
$file_id = "abc1";
// Set the file name
$file = $pdf_folder.$file_id.'.pdf';
// Remove the file if it exists to prevent errors
if(file_exists($file)) {
unlink($file);
}
// Generate the PDF
$this->container->get('knp_snappy.pdf')->generateFromHtml(
$this->renderView(
'StrimeGlobalBundle:PDF:invoice.html.twig',
$data
),
$file
);
}
}
你们知道可能是什么问题吗?
感谢您的帮助。
【问题讨论】:
-
你是如何注入容器的?为什么不直接注入 knp_snappy.pdf 呢?
-
嗨@JimL,现在这就是我的班级的样子。您如何建议将容器注入其中?您将如何直接注入 KNP?感谢您的帮助。
-
嗨@JimL,在你的帮助和 rouflak 的帮助下,我设法让它工作了。谢谢。
-
太棒了 :) 他所说的注入您需要推荐的实际服务是绝对正确的。它使测试您的服务/类变得更加容易
-
你是对的。我花了一些时间才弄清楚如何让它工作,但多亏了你们两个,我现在明白了其中的逻辑。再次感谢。 :o)
标签: php class symfony service containers