在监听器Symfony中名为“ render”的未定义方法

问题描述 投票:0回答:1

早上好,

我正在从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('[email protected]')
            ->setTo('[email protected]')
            ->setBody(
                $this->renderView(
                    // templates/emails/registration.html.twig
                    'emails/registration.html.twig',
                    ['userPseudo' => $user->getPseudo()]
                ),
                'text/html'
            );

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

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

Thx!

php symfony listener templating
1个回答
1
投票

依赖注入-了解它

您需要将Twig传递给此类(就像您对Swift Mailer所做的一样)

开始时:

use Twig\Environment;

class UserSubscriber implements EventSubscriberInterface {

private $mailer;
private $twig;

public function __construct(\Swift_Mailer $mailer, Environment $environment)
{
    $this->mailer = $mailer;
    $this->twig = $environment;
}

以及在代码(在方法中),您可以通过这种方式使用它:

$this->twig->render()

NOT

$this->renderView()
© www.soinside.com 2019 - 2024. All rights reserved.