Notification Engine

Notifications allow you to create generic notifications for your site. Some examples of this might be:

  • Sending a Welcome Email to a User
  • Broadcasting an SMS to all Admin users

The code for notifications can be found in the Core_Notify and Core_Notify_Base classes, contained in the Core module.

Creating a Notification

Specific Notifications are stored in the notify_types folder within any module. The class name must start with the module name (eg: user_) and must end with _notify. For example, a notification with the code password_reset would use a file named user_password_reset_notify.php

The class name must also match the file name, User_Password_Reset_Notify, and extend the Core_Notify_Base class.

In this example we will examine the Registration Confirmation email found in the standard User module. To create this notification, ensure the folder called notify_types exists inside the module. Then inside this folder, we will create a file named user_register_confirm_notify.php. Inside this file looks like this:

<?php

class User_Register_Confirm_Notify extends Core_Notify_Base
{
    public $required_params = array('user');

    public function get_info()
    {
        return array(
            'name'=> 'User Registration Confirmation',
            'description' => 'This message is sent to a user after successful registration.',
            'code' => 'user:register_confirm'
        );
    }

    public function get_subject()
    {
        return 'Confirmation';
    }

    public function get_content()
    {
        return file_get_contents($this->get_partial_path('email_content.htm'));
    }

    public function on_send_email($template, $params=array())
    {
        extract($params);

        $user->set_notify_vars($template, 'user_');
        $template->set_vars(array());

        $template->send($user->email, $template->content);
    }
}

Important to note about this class:

  • The public property $required_params declares what parameters are required, these will be passed in when the notification is triggered.
  • The get_info() method returns information about the notification and must return an array containing the keys: name, description and code.

The remaining methods are described in more detail later.

Triggering a Notification

When a notification is triggered, a message is created based on the supplied data and is then sent to the relevant users. Triggering a notification is designed to be very simple and can be achieved by calling a single line of code:

Core_Notify::trigger('User_Register_Confirm_Notify', array('user'=>$this));

This example will use the class we defined above to send a welcome email to a user when they first sign up to the site.