agentsquidflaps/abstract-mailer

此包已被废弃,不再维护。未建议替代包。

Symfony 邮件抽象层

dev-master 2018-04-14 19:42 UTC

This package is not auto-updated.

Last update: 2020-07-29 16:24:13 UTC


README

Maintainability codecov Build Status

这是一个简单的 symfony 邮件抽象层。非常适合简单地切换邮件提供商,无需大量重构代码。并附加了twig模板和事件集成优势。

安装只需运行...

composer require agentsquidflaps/abstract-mailer

开始时,您需要扩展抽象邮件器...

 namespace App\Mail;
 
 use Agentsquidflaps\AbstractMailer\AbstractMailer;
 
 /**
  * Class Mailer
  * @package App\Mail
  */
 class Mailer extends AbstractMailer {
    // Any other code you desire...
 }

唯一必须设置的配置是您想使用的 Swift mailer 传输...

// config/services.yaml

// These are optional, but recommended...
parameters:
  mail:
    from:
      test@test.test: Test Account Holder Name
    to: test@test.com
    
    
...a few moments later...

services:
  mailer.transport:
    class: Swift_SendmailTransport
    public: true
  App\Mail\Mailer:
    public: true
    arguments:
      - '@mailer.transport'
      // Below are optional if you've got autowiring turned on...
      - '%mail%'
      - '@your-alternative-twig-environment'
      - '@your-alternative-event-dispatcher'

所以,如果您的邮件需求发生变化,您只需更改 mailer.transport 服务即可。

要使用发送邮件,只需从邮件器对象(抽象邮件器扩展了此功能)创建 Swift_Message。例如...

$mailer
  // if not set will default to the mail.to parameter...
  ->setTo($toEmail)
  // if not set will default to the mail.from parameter...
  ->setFrom($fromEmail)
  ->setTemplate('mail/twig_mail_template.html.twig', ['pass_variables'=>$here])
  // setting mode to anything other than live, will do everything except send the email...
  ->setMode('test')
  ->setSubject('Super Cool Fun Email Subject!!!')
  ->send()
;

唯一的要求是设置一个twig模板,然后发送。

您注意到了事件分发器部分吗?是的,您可以监听/订阅事件。以下是一个订阅者示例...

namespace App\EventSubscriber;

use App\Mail\Mailer;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class MailerSubscriber
 * @package App\EventSubscriber
 */
class MailerSubscriber implements EventSubscriberInterface
{

    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            Mailer::EVENT_PRE_SEND => 'preSend',
            Mailer::EVENT_POST_SEND => 'postSend',
        ];
    }

    public function preSend()
    {
        $this->logger->info('This was sent from the mailer preSend event');
    }
    
    public function postSend()
    {
        $this->logger->info('This was sent from the mailer postSend event');
    }
}