无法在Symfony 4服务上注入模板

时间:2018-03-18 05:28:58

标签: symfony symfony4

我有以下课程:

EmailNotification

namespace App\Component\Notification\RealTimeNotification;

use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

use App\Component\Notification\NotificationInterface;

class EmailNotification implements NotificationInterface
{   
    private $logNotification;

    public function __construct(LogNotification $logNotification, \Swift_Mailer $mailer,  EngineInterface $twigEngine)
    {
        $this->logNotification = $logNotification;
    }

    public function send(array $options): void
    {
        $this->logNotification->send($options);

        dump('Sent to email');
    }
}

我的yml上有以下服务定义:

app.email_notification:
    class: App\Component\Notification\RealTimeNotification\EmailNotification
    decorates: app.log_notification
    decoration_inner_name: app.log_notification.inner
    arguments: ['@app.log_notification.inner', '@mailer', '@templating']

但是,当我试图运行我的应用程序时,会抛出一个异常说:

  

无法自动连接服务   “应用程序\分量\通知\ RealTimeNotification \ EmailNotification”:   方法“__construct()”的参数“$ twigEngine”具有类型   “Symfony \ Bundle \ FrameworkBundle \ Templating \ EngineInterface”但是这个   没找到上课。

为什么会这样?

谢谢!

3 个答案:

答案 0 :(得分:25)

你必须安装symfony / templating

composer require symfony/templating

稍微更改一下config / packages / framework.yaml

framework:
    templating:
        engines:
            - twig

答案 1 :(得分:6)

您很可能没有在您的项目中包含模板,在Symfony 4中您必须明确要求:

composer require symfony/templating

答案 2 :(得分:0)

我设法通过Twig Environment和HTTP Response做到了

<?php
use Twig\Environment;
use Symfony\Component\HttpFoundation\Response;

class myClass
{

    private $twig;

    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public function render_template($msg)
    {
        return new Response($this->twig->render('myTemplate.html.twig');
    }
}