On the weekend, Felix Geisendörfer (aka the_undefined) presented an email solution for CakePHP based on the ActionMailer class from Ruby on Rails. It inspired me to think about this topic.

The result of this thinking is a proof-of-concept implementation of a mailer component which uses models (and some of Felix’ code). You can download it from CakeForge. Feedback is welcome :)

Here an example of how the approach works. As mentioned above, it uses models for storing the mail data. As a convention, such models must have the instance variables $from, $to, $subject, and $message. I overwrite the save function in this example to set the mail data, but you can also set the data directly, or in one or more custom functions.

// app/models/confirmation_mail.php
class ConfirmationMail extends AppModel
{
    var $useTable = false;

    var $from = 'me@mydomain.com';
    var $to = '';
    var $subject = 'Confirmation';
    var $message = '';

    function save($data)
    {
        $this->to = $data[$this->name]['to'];
        $this->message = $data[$this->name]['username'] . ‘, thanks for subscribing.’;

        return true;
    }
}

The controller is simple: we “save” the data in our mail model, and send the email.

// app/controllers/example_controller.php
class ExampleController extends AppController
{
    var $uses = array('ConfirmationMail');
    var $components = array('Mailer');

    function test()
    {
        $this->data['ConfirmationMail']['to'] = ‘testuser@domain.com’;
        $this->data['ConfirmationMail']['username'] = ‘testuser’;
        $this->ConfirmationMail->save($this->data);
        $this->Mailer->send($this->ConfirmationMail);
    }
}

So, what do you think about this approach?