Send Email When New Comment Is Posted?

What is the yii way to send an email whenever a new comment is posted to my site? Note I am not using any pre-packaged comment extension.

The first thing that comes to mind is to write code to send an email in my controller when a new comment is successfully saved. However I’m wondering if it would be better to do this using an event or some other more sophisticated method.

you can setup a console app to do you offline task. if you do it thru your controller its gonna slow your app down all your other requests will be in the queue till that request is finish

yii has very good documentaion for this please do take look at the guides

I read the documentation for console apps. However, I don’t see the bigger picture. Are you suggesting that the controller kicks off a console task asynchronously? Or perhaps putting email info into a database queue table and cron task that pulls emails off the queue?

I think he’s proposing the last approach. Can you give a rough estimate on how many recepients ther will be? If there aren’t too many, it might be feasible to fire off those mails in your model’s afterSave() method. Another solution would be to register a custom shutdown function for your controller.

For this particular problem there will be a single recipient, the site administrator, so that is the solution I’m most interested in. However, out of curiosity and for future reference I would additionally like to know the best practice for sending out email to multiple recipients.

As Da:Sourcerer already suggested, i would also do this from the afterSave() method of your model. The reason is, that this notification email is part of your main business logic: It should probably always happen, whenever a new comment is created, no matter where you do that in your code. So say, you later build an API, and expose a “create comment” method there. Then you don’t have to copy the logic to send the email from the controller. It all happens automatically from your model.

if you that in the model what if you have problem with your emails server for instance your server will wait for that particular request to finish and then process the rest. I normally save them in the database and run a cronjob.

Of course you would not write the code that really sends the email in the model. You’d leave that job to some email component (which can use a queue in DB and a cron job to process them, or whatever you find adequate). But you can trigger email creation from the model.

@Mike I misunderstood you right, thats what i suggested