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

iam*_*015 12 symfony symfony4

我有以下课程:

电子邮件通知

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

我的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']
Run Code Online (Sandbox Code Playgroud)

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

无法自动服务"App\Component\Notification\RealTimeNotification\EmailNotification":方法"__construct()"的参数"$ twigEngine"具有"Symfony\Bundle\FrameworkBundle\Templating\EngineInterface"类型,但未找到此类.

为什么会这样?

谢谢!

小智 28

你必须安装symfony/templating

composer require symfony/templating
Run Code Online (Sandbox Code Playgroud)

改变一点config/packages/framework.yaml

framework:
    templating:
        engines:
            - twig
Run Code Online (Sandbox Code Playgroud)

  • 对于那些想知道的人,你必须在`framework.yaml`中添加配置部分以进行自动装配以加载Templating组件. (3认同)

Mac*_*408 11

I managed to do it with Twig Environment and HTTP Response

<?php

namespace App\Controller;

use Twig\Environment;
use Symfony\Component\HttpFoundation\Response;

class MyClass
{
    private $twig;

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

    public function renderTemplateAction($msg)
    {
        return new Response($this->twig->render('myTemplate.html.twig'));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是首选方法,因为不建议使用Symfony 4.3作为“模板”组件。一少依赖! (2认同)

Mak*_*akG 6

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

composer require symfony/templating
Run Code Online (Sandbox Code Playgroud)

  • 我现在注入的是\ Twig_Environment,我认为现在就足够了。 (4认同)
  • 我确实有,我检查了三倍。 (3认同)
  • @iamjc015 当你运行 `php bin/console debug:autowiring` 时,你看到 `Symfony\Component\Templating\EngineInterface` 类了吗?它应该是`templating.engine.twig`的别名。您的 framework.yaml 文件中是否有“模板”条目? (2认同)