【问题标题】:Set Mailable header via a trait?通过特征设置 Mailable 标头?
【发布时间】:2017-08-17 19:44:04
【问题描述】:

我正在创建一个 Laravel 包,它可以从电子邮件的使用中受益。当用户使用我的包时,他们会希望通过电子邮件发送由包创建的文件,但还要为电子邮件设置一些自定义标头。

在一个理想的解决方案中,我希望开发人员可以在他们的可邮寄类上简单地use,它会自动设置该电子邮件的标题,而无需任何额外的代码。这是否甚至可以通过使用特征来实现?

一些解决方案建议通过将其放在 build 方法中来为邮件添加标头:

$this->withSwiftMessage(function ($message) {
    $headers = $message->getHeaders();
    $headers->addTextHeader('mime', 'text/calendar');
});

但是有没有办法让我自己的自定义特征搭载在使用它的 Mailable 的 build 方法上,而不必在 Mailable 类本身中编写它?

【问题讨论】:

    标签: laravel email header swiftmailer


    【解决方案1】:

    使用特征的解决方案

    能够使用 trait 做到这一点的唯一方法是在你的 trait 中定义 build 方法并让你的用户定义另一个函数而不是 build 以便你可以直接操作实际使用的函数由Mailable 类。

    所以你的特点是:

    trait IsMailable {
    
    
         public function build()
         {
              $this->withSwiftMessage(function ($message) {
                  $headers = $message->getHeaders();
                  $headers->addTextHeader('mime', 'text/calendar');
              });
    
              if(!method_exists($this, 'buildMail')) throw \Exception('buildMail is not defined!');
              return $this->buildMail();
          }
    
    
    
    }
    

    因此您的用户必须定义​​方法buildMail 而不是build

    最佳解决方案

    恕我直言,最佳解决方案是扩展类 Illuminate\Mail\Mailable 重新定义方法 send 并让最终用户实现这个新定义的类而不是 Illuminate\Mail\Mailable

    所以你的班级是:

    class Mailable extends \Illuminate\Mail\Mailable {
    
        /**
        * Send the message using the given mailer.
        *
        * @param  \Illuminate\Contracts\Mail\Mailer  $mailer
        * @return void
        */
        public function send(MailerContract $mailer)
        {
            $this->withSwiftMessage(function ($message) {
                $headers = $message->getHeaders();
                $headers->addTextHeader('mime', 'text/calendar');
            });
    
            parent::send($mailer);
        }
    }
    

    这样做,您的用户可以像使用标准 Illuminate\Mail\Mailable 类一样使用 build 方法,但最终结果将是您的类捎带您实际需要的其他信息。

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 2010-12-08
      • 2019-09-03
      • 2017-01-29
      • 2013-09-27
      • 2021-08-27
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多