如何在控制器或视图之外使用Zend Framework部分视图助手?

时间:2010-07-16 19:58:33

标签: php email zend-framework partial-views html-email

我想创建一个生成HTML电子邮件的自定义类。我希望电子邮件的内容来自“电子邮件视图脚本”目录。所以概念是我可以像创建普通视图脚本(能够指定类变量等)一样创建HTML电子邮件视图脚本,并且视图脚本将呈现为电子邮件的HTML主体。

例如,在控制器中:

$email = My_Email::specialWelcomeMessage($toEmail, $firstName, $lastName);
$email->send();

My_Email::specialWelcomeMessage()函数会执行以下操作:

public static function specialWelcomeMessage($toEmail, $firstName, $lastName) {
    $mail = new Zend_Mail();
    $mail->setTo($toEmail);
    $mail->setFrom($this->defaultFrom);
    $mail->setTextBody($this->view->renderPartial('special-welcome-message.text.phtml', array('firstName'=>$firstName, 'lastName'=>$lastName));
}

理想情况下,最好能找到一种方法让specialWelcomeMessage()函数像这样简单:

public static function specialWelcomeMessage($toEmail, $firstName, $lastName) {
    $this->firstName = $firstName;
    $this->lastName = $lastName;
    //the text body and HTML body would be rendered automatically by being named $functionName.text.phtml and $functionName.html.phtml just like how controller actions/views happen
}

然后会呈现特殊的welcome-message.text.phtml和special-welcome-message.html.phtml脚本:

<p>Thank you <?php echo $this->firstName; ?> <?php echo $this->lastName; ?>.</p>

如何从视图脚本或控制器外部调用部分视图助手?我是以正确的方式接近这个吗?或者这个问题有更好的解决方案吗?

1 个答案:

答案 0 :(得分:11)

怎么样:

public static function specialWelcomeMessage($toEmail, $firstName, $lastName) {
    $view = new Zend_View;
    $view->setScriptPath('pathtoyourview');
    $view->firstName = $firstName;
    $view->lastName = $lastName;
    $content = $view->render('nameofyourview.phtml');
    $mail = new Zend_Mail();
    $mail->setTo($toEmail);
    $mail->setFrom($this->defaultFrom);
    $mail->setTextBody($content);
}

如果您希望使用您所说的动作名称动态更改脚本路径,为什么不使用获取您正在调用的动作名称或控制器并将其作为变量发送,或者更好的是默认参数。这将有所帮助:

http://framework.zend.com/manual/en/zend.controller.request.html