php静态电子邮件类

时间:2012-10-18 21:56:52

标签: php phpmailer

我是新手,我试图创建一个使用phpmailer类的静态电子邮件类。

我想做的事情就像......

Email::send('from', 'to', 'subject', 'html message'); // works

但如果我想添加附件......

Email::send('from', 'to', 'subject', 'html message')->attach('file/blah.txt');

这会引发一个致命错误:Call to undefined method PHPMailer::attach(),我明白为什么,我只是不知道该怎么做才能让Email类做上面的代码,如果它甚至可能的话。

以下是我的实验。

class Email {

    static $attach;

    public static function send($from, $to, $subject, $message)
    {
        $email = new PHPmailer();

        try {

            $email->AddAddress($to);
            $email->SetFrom($from);
            $email->Subject = $subject;
            $email->MsgHTML($message);

            if (self::$attach) $email->AddAttachment(self::$attach);        

            $email->Send();
        }
        catch (phpmailerException $e)
        {
            return $e->errorMessage();
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }

        return $email;
    }

    public static function attach($attachment)
    {
        self::$attach = $_SERVER['DOCUMENT_ROOT'].$attachment;
    }
}

2 个答案:

答案 0 :(得分:2)

你的API没有任何意义。为了做你想要用链接做的事情你需要使用实例,但你也可以使用静态来更像你想要的界面:

class Email {

    protected $attchements = array();
    protected $mailer;

    public function __construct($from, $to, $subject, $message) {
          $this->mailer = new PHPMailer();

          $this->mailer->AddAddress($to);
          $this->mailer->SetFrom($from);
          $this->mailer->Subject = $subject;
          $this->mailer->MsgHTML($message);

    }

    public static function create($from, $to, $subject, $message) {
        $instance = new Self($from, $to, $subject, $message);
        return $instance;

    }

    public static function createAndSend($from, $to, $subject, $message) {
         $instance = new Self($from, $to, $subject, $message);
         return $instance->send();
    }

    public function send()
    {
       if(!empty($this->attachments)) {
           foreach($this->attachments as $attachment) {
               $this->mailer->AddAttachment($attachment);
           }
       }

       return $this->mailer->send();        
    }

    public function attach($attachment)
    {
        $this->attachments[] = $_SERVER['DOCUMENT_ROOT'].$attachment;
        return $this;
    }
}

因此,您的用法如下:

//simple
Email::createAndSend($to, $from, $subject, $message);

// with attachment
Email::create($to, $from, $subject, $message)
   ->attach('fileone.txt')
   ->attach('filetwo.txt')
   ->send();

还应该注意我从你的例子中取出了你的异常处理......你应该整合那个...我只是为了保持简短和甜蜜而做到了: - )

答案 1 :(得分:0)

Fluent指令适用于对象(与静态类不同)。

在您的情况下,只需反转指令:

Email::attach('file/blah.txt');
Email::send('from', 'to', 'subject', 'html message');

但真正的物体可能会更好。