Cho phép có một vết nứt nhỏ ở đây :)
class Emailer
{
var $recipients = array();
var $EmailTemplate;
var $EmailContents;
public function __construct($to = false)
{
if($to !== false)
{
if(is_array($to))
{
foreach($to as $_to){ $this->recipients[$_to] = $_to; }
}else
{
$this->recipients[$to] = $to; //1 Recip
}
}
}
function SetTemplate(EmailTemplate $EmailTemplate)
{
$this->EmailTemplate = $EmailTemplate;
}
function send()
{
$this->EmailTemplate->compile();
//your email send code.
}
}
Thông báo chức năng SetTemplate()
...
Heres aa lớp mẫu nhỏ
class EmailTemplate
{
var $variables = array();
var $path_to_file= array();
function __construct($path_to_file)
{
if(!file_exists($path_to_file))
{
trigger_error('Template File not found!',E_USER_ERROR);
return;
}
$this->path_to_file = $path_to_file;
}
public function __set($key,$val)
{
$this->variables[$key] = $val
}
public function compile()
{
ob_start();
extract($this->variables);
include $this->path_to_file;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
Dưới đây là một ví dụ nhỏ, bạn vẫn cần phải làm cốt lõi của tập lệnh nhưng điều này sẽ cung cấp cho bạn bố cục đẹp để bắt đầu.
$emails = array(
'[email protected]',
'[email protected]'
);
$Emailer = new Emailer($emails);
//More code here
$Template = new EmailTemplate('path/to/my/email/template');
$Template->Firstname = 'Robert';
$Template->Lastname = 'Pitt';
$Template->LoginUrl= 'http://stackoverflow.com/questions/3706855/send-email-with-a-template-using-php';
//...
$Emailer->SetTemplate($Template); //Email runs the compile
$Emailer->send();
Thats thực sự tất cả những gì được với nó, chỉ cần biết cách sử dụng các đối tượng và nó khá đơn giản từ đó, ooh và mẫu sẽ trông một chút gì đó như thế này:
Welcome to my site,
Dear <?php echo $Firstname ?>, You have been registered on our site.
Please visit <a href="<?php echo $LoginUrl ?>">This Link</a> to view your upvotes
Regards.
Chỉ cần rực rỡ! – Jeff
Làm tốt lắm. Câu lệnh trích xuất trong phương thức biên dịch có cần đặt trước câu lệnh include không? –
Không cần phải gọi trước khi được tải, điều này cho phép xác định các biến mẫu và trong phạm vi cho nội dung mẫu. – RobertPitt