在 Yii 中存储电子邮件模板的最佳方法


The best approach to store email templates in Yii

我现在正在实现一个功能,允许向在我的 Yii 1.1 项目中注册的用户发送系统电子邮件。

我是一个初学者开发人员,所以我有时仍然需要一个提示,所以我有几个关于存储和检索电子邮件模板文件的实现的简单问题,这些文件将在发送系统消息时使用(例如,使用 swiftMailer)。

  1. Yii 应用程序的哪个文件夹最适合存储系统消息的 HTML 电子邮件模板?
  2. 我的"电子邮件模板"模型应该扩展哪个类,因为电子邮件模板将存储为文件,并且模型不会与数据库交互。
  3. 这种方法(单独的"电子邮件模板"模型+在系统上存储电子邮件模板文件)是否适合此类事情?

如果有人可以建议以不同的方式做事,那也将不胜感激。

电子邮件与

其他类型的视图没有什么不同,只是它们的传递机制不同。以下是 Yii 期望你的模板所在的地方:

yii/
-- protected/
   -- views/
      -- mail/
         -- template.html

您可以在 Yii 中为您的电子邮件指定模板。请参阅YiiMailMessage->setBody的文档:

/**
* Set the body of this entity, either as a string, or array of view 
* variables if a view is set, or as an instance of 
* {@link Swift_OutputByteStream}.
* 
* @param mixed the body of the message.  If a $this->view is set and this 
* is a string, this is passed to the view as $body.  If $this->view is set 
* and this is an array, the array values are passed to the view like in the 
* controller render() method
* @param string content type optional. For html, set to 'html/text'
* @param string charset optional
*/

例:

$message = new YiiMailMessage;
$message->view = 'main_tpl';
$message->setBody(array(
    'data' => $data,
    'user' => $user,
));
$message->subject = $subject;
$message->addTo($email);
$message->from = $from;
Yii::app()->mail->send($message);

这会使用 yii/protected/views/mail/main_tpl.php 模板准备一条消息,并将其与 $data$user一起发送以填充缺失的部分。