Symfony2 - 添加Swiftmailer作为服务

时间:2014-08-27 02:54:06

标签: email symfony service swiftmailer

我想将我的电子邮件代码从我的控制器移到服务中。

到目前为止,我已完成以下操作:

  • 在services.yml

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

可以在EmailManager.php中使用一些帮助以及如何在控制器中调用它吗?

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的控制器代码,我想将其从控制器移出到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';
}
}

1 个答案:

答案 0 :(得分:7)

您可以根据需要自定义此项,但这是一个大致的想法和非常快速的草稿来指导您:

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();
}

改善空间

你可以:

  • email data model ,其中包含电子邮件所需的字段(例如$subject$recipientEmail,...)
  • composer ,将根据您的请求撰写您的电子邮件
  • 发送电子邮件的 sender

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..

}

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

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

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

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

    return $email;
}

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

中只有功能,那么它们会是什么样子