In an app of mine we send a lot of email. It may be that we do it in response to an action (user sign up, admin posts something, someone replies to something), or it may be directed by the admin (bulk email all members).
What I’m currently doing is sending the emails in a loop in the controller action. While simple to code, its slow and I have decided to implement an email queue and cronjob to send queued email.
Since I’m already re-architecting this I am wondering if I should be writing this duplicative code in all my controller actions. You know, new queue object. Assign data to object properties. Save queue.
Is there a better way? I was reading about behaviors or components but not really sure if this fits this situation.
There are several ways that you can go about this. To avoid code duplication, you need to write a single ‘sendMail’ function’ somewhere to add your mails to the queue.
[list=1][size=2]Make sendMail available as a static method in a Utility class;[/size][size=2]2)[/size][size=2]Put sendMail in an ApplicationComponent and use it with ‘Yii::app()->mail->sendMail()’.
[size=2]The advantage is that you’ll be able to configure the mailserver, etc in the configuration file.
[/size][/size][size=2][The component can be put in an extension].[/size][*][size=2]Put sendMail in a behavior and add this behavior to the classes where you need it.
[/size][size=2]This implies that only the class using sendMail is aware of the mailer, and not the ‘application’ (because you need to setup the application component in ‘2’), but I do not prefer this method as it requires you to add the behavior everywhere you use the method.[/size][*]Put the above in a Module.
And think about more features (table creation, reporting) and get a performant message management system for Yii.
[Do not limit the module to mails, but make it flexible to apply it to SMS, Push (Android/Apple/…), logging, proxying/factory method to use a "messager" depending on the destination, etc.].[/list]