我有一个简单的 Email() 类。它用于从我的网站发送电子邮件。
<?
Email::send($to, $subj, $msg, $options);
?>
我还有一堆用纯 HTML 编写的电子邮件模板,其中穿插了一些 PHP 变量。例如。 /inc/email/templates/account_created.php
:
<p>Dear <?=$name?>,</p>
<p>Thank you for creating an account at <?=$SITE_NAME?>. To login use the link below:</p>
<p><a href="https://<?=$SITE_URL?>/account" target="_blank"><?=$SITE_NAME?>/account</a></p>
为了呈现 PHP 变量,我必须将模板 include
到我的函数中。但由于 include
不返回内容,而是直接将其发送到输出,我不得不用缓冲函数包装它:
<?
abstract class Email {
public static function send($to, $subj, $msg, $options = array()) {
/* ... */
ob_start();
include '/inc/email/templates/account_created.php';
$msg = ob_get_clean();
/* ... */
}
}
之后我意识到 PHP 变量没有被渲染,因为它们在函数范围内,所以我不得不在模板中全局化变量:
<?
global $SITE_NAME, $SITE_URL, $name;
?>
<p>Dear <?=$name?>,</p>
...
那么问题来了,有没有更优雅的解决方案呢?我主要担心使用 ob_start()
和 global
的解决方法。出于某种原因,这在我看来很奇怪。或者这几乎是常见的做法?
最佳答案
您可以在this answer 中找到更优雅的解决方案。 .
注意 PHP extract 的用法实例化模板变量的函数。
换句话说,您应该将模板解析逻辑移到电子邮件发送功能之外。
例如:
<?php
class SimpleTemplate {
private $_tpl = "";
private $_vars = array();
function __construct($tpl_name) {
$this->_tpl = $tpl_name;
}
public function __set($name, $value) {
$this->_vars[$name] = $value;
}
public function setVars($values) {
$this->_vars = $values;
}
public function parse() {
ob_start();
extract($this->_vars);
include $this->_tpl;
return ob_get_clean();
}
}
abstract class Email {
public static function send($to, $subj, $msg, $options = array()) {
/* ... */
}
}
$tpl = new SimpleTemplate('/inc/email/templates/account_created.php');
$tpl->name = 'Stack Overflow';
$tpl->SITE_NAME = 'site_name';
$tpl->SITE_URL = 'localhost';
Email::send("me@localhost", "Subject", $tpl->parse());
?>
关于php - 使用模板的电子邮件功能。通过 ob_start 和全局变量包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13767135/