0

这是我的订阅者类。我想让用户电子邮件给他一封电子邮件。我在这里使用 EntityManagerInterface

use Doctrine\ORM\EntityManagerInterface;

final class RegisterMailSubscriber implements EventSubscriberInterface
{
    private $mailer;

    public function __construct(\Swift_Mailer $mailer, EntityManagerInterface $entityManager)
    {
        $this->mailer = $mailer;
        $this->repository= $entityManager->getRepository('AppEntity:User');
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['sendMail', EventPriorities::POST_WRITE],
        ];
    }

    public function sendMail(ViewEvent $event): void
    {
        $user = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$user instanceof User || Request::METHOD_POST !== $method) {
            return;
        }
        $userInfo = $this->repository->find($user->getId());
        
    }
}
4

1 回答 1

1

您需要导入用作 User、Request、ViewEvent、KernelEvent 等的所有依赖项。

顺便说一句,导入存储库 (UserRepository) 而不是 entityManager 是一个很好的做法,但您不需要它,因为您已经拥有 $user。你不需要再次找到它。

如果您在这些名称空间(位置)中有用户类,我认为这应该足够了:

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;

final class RegisterMailSubscriber implements EventSubscriberInterface
{
    private $mailer;

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

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['sendMail', EventPriorities::POST_WRITE],
        ];
    }

    public function sendMail(ViewEvent $event): void
    {
        $user = $event->getControllerResult(); 
        $method = $event->getRequest()->getMethod();

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

       $userEmail = $user->getEmail(); //for example. You got the user 5 lines before.
        
    }
}
于 2020-06-23T22:15:14.590 回答