简体   繁体   中英

How do I call a function before every email send?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM