Symfony2 - 添加Swiftmailer作为服务 [英] Symfony2 - Adding Swiftmailer as a service

查看:228
本文介绍了Symfony2 - 添加Swiftmailer作为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经完成了以下工作:




  • 在services.yml中创建条目


  • 在里面创建一个EmailManager.php文件acme / demobundle / services / EmailManager.php




可以对需要进入EmailManager.php的一些帮助如何在控制器中调用?



services.yml

 服务:
email_manager:
类:Acme\DemoBundle\Services\EmailManager
参数:[@request_stack,@mailer]
范围:请求

EmailManager.php

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

命名空间Acme\DemoBundle\\ \\服务;

class EmailManager
{
private $ mailer;
private $ request;

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

什么需要去这里?我只需将下面的contactAction中的代码复制/粘贴到这里?

}

我想要具有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 @ gmail.com')
- > setBody(
$ this-> renderView(
'AcmeDemoBundle:默认值:index.html.twig',
数组(
'ip'=> $ request-> getClientIp(),
'name'=> $ form-> get('name') - > getData(),
'消息'=> $ form-> get('message') - > getData()


);

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

$ request-> getSession() - > getFlashBag() - > add('success','您的电子邮件已发送!

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

返回数组(
'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你的名字?',
'pattern'=>'。{2,}'// minlength

))
- > add('email'电子邮件',数组(
'attr'=>数组(
'占位符'=>'所以我可以回到你'

))
- > add('subject','text',array(
'attr'=> array(
'placeholder'=>'您的消息的主题',
'pattern'=>'。{3,}'// minlength

))
- > add('message','textarea',array $ b ATTR =>阵列(
‘的cols’=大于90,
‘行’=大于10,
‘占位符’=> '你的信息给我...'

));
}

public function setDefaultOptions(OptionsResolverInterface $ resolver)
{
$ collectionConstraint = new Collection(array(
'name'=> array
new NotBlank(array('message'=>'Name not not be blank。')),
new Length(array('min'=> 2))

'email'=>数组(
new NotBlank(array('message'=>'Email does not be blank。')),
new Email(array('message' =''无效的电子邮件地址'))
),
'subject'=>数组(
new NotBlank(array('message'=>'主题不应为空。'))
new Length(array('min'=> 3))
),
'message'=>数组(
new NotBlank(array 'message'=>'消息不应为空。'))
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();
}






h2>

您可以:




  • 电子邮件数据模型 ,其中包含电子邮件所需的字段(如 $ subject $ recipientEmail ,...)

  • 一个 作曲家 请求

  • 将发送您的电子邮件

  • 发件人 >

    EMAIL MODEL 将如下所示:

      / ** 
    *电子邮件数据模型
    * /
    类电子邮件实现EmailInterface
    {
    / **
    *消息的文本部分。
    *
    * @var string
    * /
    protected $ bodyText;

    // etc ... etc ..

    }

    你还会有一个 EmailInterface

      / ** 
    *电子邮件界面
    * /
    接口EmailInterface
    {

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

    // etc ... etc ..

    }

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

      public函数send(EmailInterface $ email)
    {
    // ...
    }

    THE COMPOSER 将如下所示(如果保存在EmailManager中):

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

    return $ email;
    }

    注意: 作曲家和发件人也可以单独提供更好的重用服务,这取决于你。如果您的 EmailManager


    中只有函数,那么它们会是什么样子

    I'd like to move my email code from my controller into a service.

    I've done the following thus far:

    • created the entry in services.yml

    • created a EmailManager.php file inside acme/demobundle/services/EmailManager.php

    Could use some help on what needs to go into the EmailManager.php and how to call it in the 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?
    
    }
    

    Controller code with contactAction that I would like to move out of the controller into EmailManager service:

    /**
     * @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 Form

    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';
    }
    }
    

    解决方案

    You can customize this as you see fit, but that's a general idea and a very quick draft to guide you:

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


    Room for Improvement

    You could have:

    • An email data model that would contain the fields necessary for an email (like $subject, $recipientEmail, ...)
    • A composer that would compose your email from your request
    • A sender that would send your email

    EMAIL MODEL would look something like this:

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

    You'd have an EmailInterface too:

    /**
     * Email interface
     */
    interface EmailInterface
    {
    
        /**
         * @return string
         */
        public function getBodyText();
    
        // etc...etc..
    
    }
    

    THE SENDER would look like this (if kept inside EmailManager):

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

    THE COMPOSER would look like this (if kept inside EmailManager):

    public function composeEmail(Request $request)
    {
        //...
    
        return $email;
    }
    

    Note: Composer and Sender could also be a separate service for better reuse, that's up to you I guess. Here is what they would look like if there were just functions in your EmailManager

    这篇关于Symfony2 - 添加Swiftmailer作为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆