douruoshen1449
2015-10-05 21:24
浏览 40
已采纳

如何在每封电子邮件发送前调用一个函数?

I have about 50 different email templates whose text changes dynamically based on who the recipient is. Rather than make a different template for every possible case and include similar logic across dozens of different controller files, I want to include some case switching within each template and apply a case determining variable to every email.

For example a typical template might look like this:

<? if ($case) { ?>
    <p> text variation 1 </p>
<? } else { ?>
    <p> text variation 2 </p>
<? } ?>

$case would be set by a function beforeEmail($to_address) that does all the calculations for the cases based on the recipients email. These calculations are the same for every single email. How can I get beforeEmail() to get called every time an email sends? Or more accurately, where do I put a beforeEmail() function?

Normally I would stick this kind of code in the view files controller, but email view-files don't have a controller. I've played around with making beforeEmail() a static function somewhere and call it in each view file, but that just seems messy and wrong (It leaves me with function calls inside view files, and duplicate code accross 50+ files).

Edit: I also tried setting the $case variable in a layout file, but it turns out layouts are loaded AFTER the email view file is, so variables set inside a layout can't be used in a view file.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • donglu2761 2015-10-14 04:27
    已采纳

    In case anyone has a similar problem, I ended up modifying the core CakeEmail libraries send() method. While it's not ideal, it was the only way I could find to get the behavior I wanted (Without creating duplicate code everywhere).

    Things that don't work:

    -Callbacks/events - The CakeEmail class doesn't offer callbacks.

    -Creating a custom transport - Transports are called after the email is rendered.

    -Putting code in a common layout file - Layouts are rendered after the email's view file is rendered.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题