email - Symfony2 - 添加 Swiftmailer 作为服务

标签 email symfony service swiftmailer

我想将我的电子邮件代码从我的 Controller 移动到服务中。

到目前为止,我已经完成了以下工作:

  • 在 services.yml 中创建条目

  • 在 acme/demobundle/services/EmailManager.php 中创建了一个 EmailManager.php 文件

能否就需要进入 EmailManager.php 的内容以及如何在 Controller 中调用它提供一些帮助?

services.yml

services:
email_manager:
    class: Acme\DemoBundle\Services\EmailManager
    arguments: [@request_stack, @mailer]
            scope: request

EmailManager.php

<?php
// src/Acme/DemoBundle/Services/EmailManager.php

namespace Acme\DemoBundle\Services;

class EmailManager
{
private $mailer;
private $request;

public function __construct(RequestStack $requestStack, $mailer)
{
    $this->request = $requestStack->getCurrentRequest();
    $this->mailer  = $mailer;
}

What needs to go here? Do I just copy/paste the code from the contactAction below into here?

}

带有 contactAction 的 Controller 代码,我想将其从 Controller 移出到 EmailManager 服务中:

/**
 * @Route("/", name="contact")
 * @Template("AcmeDemoBundle:Default:index.html.twig")
 */
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());

if ($request->isMethod('POST')) {
    $form->submit($request);

    if ($form->isValid()) {
        $message = \Swift_Message::newInstance()
            ->setSubject($form->get('subject')->getData())
            ->setFrom($form->get('email')->getData())
            ->setTo('example@gmail.com')
            ->setBody(
                $this->renderView(
                    'AcmeDemoBundle:Default:index.html.twig',
                    array(
                        'ip' => $request->getClientIp(),
                        'name' => $form->get('name')->getData(),
                        'message' => $form->get('message')->getData()
                    )
                )
            );

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

        $request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!');

        return $this->redirect($this->generateUrl('contact'));
    }
}

return array(
    'form' => $form->createView()
);
}

ContactType 表单

class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('name', 'text', array(
    'attr' => array(
        'placeholder' => 'What\'s your name?',
        'pattern'     => '.{2,}' //minlength
    )
))
    ->add('email', 'email', array(
        'attr' => array(
            'placeholder' => 'So I can get back to you.'
        )
    ))
    ->add('subject', 'text', array(
        'attr' => array(
            'placeholder' => 'The subject of your message.',
            'pattern'     => '.{3,}' //minlength
        )
    ))
    ->add('message', 'textarea', array(
        'attr' => array(
            'cols' => 90,
            'rows' => 10,
            'placeholder' => 'And your message to me...'
        )
    ));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $collectionConstraint = new Collection(array(
        'name' => array(
            new NotBlank(array('message' => 'Name should not be blank.')),
            new Length(array('min' => 2))
        ),
        'email' => array(
            new NotBlank(array('message' => 'Email should not be blank.')),
            new Email(array('message' => 'Invalid email address.'))
        ),
        'subject' => array(
            new NotBlank(array('message' => 'Subject should not be blank.')),
            new Length(array('min' => 3))
        ),
        'message' => array(
            new NotBlank(array('message' => 'Message should not be blank.')),
            new Length(array('min' => 5))
        )
    ));

    $resolver->setDefaults(array(
        'constraints' => $collectionConstraint
    ));
}

public function getName()
{
    return 'contact';
}
}

最佳答案

您可以根据需要对其进行自定义,但这是一个总体思路,也是一个非常快速的草稿,可以指导您:

public function send($subject, $recipientName, $recipientEmail, $bodyHtml, $bodyText)
{
    /* @var $mailer \Swift_Mailer */
    if(!$this->mailer->getTransport()->isStarted()){
        $this->mailer->getTransport()->start();
    }

    /* @var $message \Swift_Message */
    $message = $this->mailer->createMessage();
    $message->setSubject($subject);

    $message->setBody($bodyHtml, 'text/html');
    $message->addPart($bodyText, 'text/plain', 'UTF8');

    $message->addTo($recipientEmail, $recipientName);
    $message->setFrom( array('example@gmail.com' => 'Chance') );

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

改进空间

你可以:

  • 一个电子邮件数据模型,其中包含电子邮件所需的字段(例如$subject$recipientEmail, ...)
  • composer 将根据您的请求撰写您的电子邮件
  • 将向您发送电子邮件的发件人

EMAIL MODEL 看起来像这样:

/**
 * Email Data Model
 */
class Email implements EmailInterface
{
    /**
     * The text part of the message.
     *
     * @var string
     */
    protected $bodyText;

    // etc...etc..

}

你也会有一个EmailInterface:

/**
 * Email interface
 */
interface EmailInterface
{

    /**
     * @return string
     */
    public function getBodyText();

    // etc...etc..

}

THE SENDER 看起来像这样(如果保存在 EmailManager 中):

public function send(EmailInterface $email)
{
    //...
}

THE COMPOSER 看起来像这样(如果保存在 EmailManager 中):

public function composeEmail(Request $request)
{
    //...

    return $email;
}

注意: Composer 和 Sender 也可以是单独的服务以更好地重用,我想这取决于您。如果您的 EmailManager

中只有函数,它们会是这样的

关于email - Symfony2 - 添加 Swiftmailer 作为服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25518215/

相关文章:

web-services - 服务可以在其代码中调用另一个服务吗?

REST Web 服务,仅用于数据库访问?

sql-server-2005 - 报告服务饼图

email - 如何从电子邮件地址识别网络邮件服务?

python - django send_mail() 函数需要几分钟

php mail() 打印神秘错误

php - Doctrine源代码: namespace or class?中 "PDOStatement extends\PDOStatement"的含义

php - Symfony 4 - 自定义身份验证 FosUserBundle

perl - 如何在 Perl 中将文件内容作为电子邮件发送?

php - 使用 Twig 创建数组