Using afterSave for e-mail notification
An introduction to Cake callbacks
What you will learn
What callbacks are and how to execute them. How to use the afterSave callback to implement e-mail notification.
What you will need
A working Cake application, even just a scaffolded one. My scaffolding tutorial will get you started.
What are callbacks?
In Cake, a callback is a way of executing some code before or after firing a Model or Controller method. For example, you might use the Model's beforeSave callback to validate the fields on your form before saving to the database.
What callbacks can I use?
Cake has several Model callbacks for you to execute:
beforeFindafterFindbeforeSaveafterSavebeforeDeleteafterDelete
and also some Controller callbacks:
beforeFilter(before the Controller method is run)beforeRender(after the method has run but before rendering)afterFilter(after the method has run and rendered)
Note: in versions prior to 0.10.8.2047 RC5 the beforeSave callback executes before the $this->ValidateErrors() method. If this is a problem, move your validation into the beforeSave call.
1. Making a callback happen
You create callbacks in your application's Model or Controller files. In this example we are sending an e-mail from the Model whenever something is saved to the database.
<?php
// File: /app/models/bookmark.php
class Bookmark extends AppModel
{
var $name = 'Bookmark';
function afterSave()
{
// mail me when a new bookmark is added
mail('example@example.com', 'Bookmark saved to database');
return true;
}
}
?>
The return true; is required, although it's more useful on callbacks like beforeSave, where returning false will actually stop the save action.
2. That's it
Sit back and watch the e-mails roll in.
Comments and feedback
Please e-mail graham at grahambird dot co dot uk