Listener Symfony 中名为“render”的未定义方法

我正在从 Symfony 上的侦听器发送邮件(Swift 邮件程序),只有在使用 renderView 时出现错误(也尝试使用 render)...


未定义的方法“renderView”。


这是我的听众:


<?php


namespace App\Events;


use ApiPlatform\Core\EventListener\EventPriorities;

use App\Entity\User;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\HttpKernel\Event\ViewEvent;

use Symfony\Component\HttpKernel\KernelEvents;


class UserSubscriber implements EventSubscriberInterface {


    private $mailer;


    public function __construct(\Swift_Mailer $mailer)

    {

        $this->mailer = $mailer;

    }


    public static function getSubscribedEvents()

    {

        return [

            KernelEvents::VIEW => ['sendMail', EventPriorities::POST_VALIDATE],

        ];

    }


    public function sendMail(ViewEvent $event): void

    {

        $user = $event->getControllerResult();

        $method = $event->getRequest()->getMethod();


        if (!$user instanceof User || Request::METHOD_POST !== $method) {

            return;

        }


        $message = (new \Swift_Message('A new book has been added'))

            ->setFrom('mail@mail.com')

            ->setTo('mail@mail.com')

            ->setBody(

                $this->renderView(

                    // templates/emails/registration.html.twig

                    'emails/registration.html.twig',

                    ['userPseudo' => $user->getPseudo()]

                ),

                'text/html'

            );


        $this->mailer->send($message);

    }

}

我知道模板服务在侦听器中不可用,但我不明白如何注入它。


qq_笑_17
浏览 160回答 1
1回答

小唯快跑啊

依赖注入 - 了解它你需要将 Twig 传递给这个类(就像你对 Swift Mailer 所做的那样)一开始:use Twig\Environment;class UserSubscriber implements EventSubscriberInterface {private $mailer;private $twig;public function __construct(\Swift_Mailer $mailer, Environment $environment){&nbsp; &nbsp; $this->mailer = $mailer;&nbsp; &nbsp; $this->twig = $environment;}并在代码中(在方法中)以这种方式使用它:$this->twig->render()不是$this->renderView()
打开App,查看更多内容
随时随地看视频慕课网APP