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 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体