通过特征设置 Mailable header?

Set Mailable header via a trait?

我正在创建一个 Laravel 包,它将受益于使用电子邮件。当用户使用我的包时,他们希望通过电子邮件发送包创建的文件,但也为电子邮件设置一些自定义 headers。

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

一些解决方案建议将 headers 添加到 mailables 中,方法是将其放入 build 方法中:

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

但是有没有办法在使用它的 Mailable 的 build 方法上拥有我自己的自定义特征 piggy-back 而不必将其写入 Mailable class 本身?

使用特征的解决方案

能够用特征做到这一点的唯一方法是在你的特征中定义 build 方法并让你的用户定义另一个函数而不是 build 这样你就可以直接Mailable class.

实际使用的函数的操作

所以你的特质是:

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

最优解

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

所以你的 class 将是:

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

这样做你的用户可以使用 build 方法,就像使用标准 Illuminate\Mail\Mailable class 一样,但最终结果是你的 class 是搭载您实际需要的附加信息。