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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端