[英]Symfony 2.8 dependecy injection issue
嗨,我在Symfony2中依赖注入服务有一个小问题,我无法弄清楚出了什么问题。我遵循了http://symfony.com/doc/current/service_container/injection_types.html中的示例。 也许有人可以将其整理出来并添加代码(我不想扩展控制器或将此作为参数传递给类构造函数):
services:
app.custom_mailer:
class: NTPBundle\Mailer\CustomMailer
arguments: ['@mailer']
CustomMailer.php
namespace NTPBundle\Mailer;
class CustomMailer {
private $mailer;
public function __construct(MailerInterface $mailer)
{
$this->mailer = $mailer;
}
public function weekExtractMail() {
$message = \Swift_Message::newInstance()
->setSubject('Hello Email')
->setFrom('no-reply@test.com')
->setTo('no-reply@test.com')
->setBody("Test"
);
$this->mailer->send($message);
return $this;
}
}
和PDFTestController.php
namespace NTPBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use \Symfony\Component\HttpFoundation\Response;
class PDFTestController extends Controller{
/**
* @Route("/pdftest")
*/
public function pdfTestAction() {
$mailer=new \NTPBundle\Mailer\CustomMailer;
$mailer->weekExtractMail();
return new response($this->renderView('NTPBundle:PDFReports:weekVolumes.html.twig', array()));
}
}
和错误
可捕获的致命错误:传递给NTPBundle \\ Mailer \\ CustomMailer :: __ construct()的参数1必须是NTPBundle \\ Mailer \\ MailerInterface的实例,没有给出,在C:\\ wamp64 \\ www \\ src \\ NTPBundle \\ Controller \\ PDFTestController.php中调用在第19行并定义
我在调试容器中查找并定义了服务。
问题似乎出在您定义服务,然后使用new实例化服务。 为了允许symfony进行其工作(并实际上注入依赖项),您需要symfony最有可能使用服务容器实例化服务:
$mailer = $container->get('app.custom_mailer');
编辑:在控制器中,您可以只使用$this->get
因为symfony为此做了一个简单的别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.