Note: You are currently viewing documentation for Moodle 3.4. Up-to-date documentation for the latest stable version of Moodle is likely available here: Events API.

Development:Events API

From MoodleDocs
Revision as of 06:44, 12 April 2007 by Martin Dougiamas (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The Events API is a new core system in Moodle to allow better communication between modules. It's based on modules triggering new events with attached data, and the other modules handling those events with custom functions.

Overview

We'll be using the example of a grade being posted from a module into the gradebook, but there are obviously all kinds of events possible.

Triggering an event

Whenever a grade is created or changed by a module, it should “tell” the system about it (in addition to any local working storage it uses). So, using the quiz as an example, we first define an object as follows:

$eventdata = new object;
$eventdata->courseid = $course->id;
$eventdata->itemname = $quiz->name;
$eventdata->itemtype = 'mod';
$eventdata->itemmodule = 'quiz';
$eventdata->iteminstance = $quiz->id;
$eventdata->itemnumber = 1;
$eventdata->iteminfo = $quiz->info;
$eventdata->idnumber = $cm->idnumber;   // new field in 1.9
$eventdata->grademax = $quiz->grade;
$eventdata->grademin = 0;
$eventdata->userid = $USER->id;
$eventdata->gradevalue = $currentvalue;

Then we post the object as an event and forget about it:

trigger_event('grade_added', $eventdata);


Handling an event

Modules can define an events.php in their db directory which defines events they want to be notified about, and describes which of their functions or class methods should be notified. For example, an export plugin could register something like:

$events = array (
   'grade_added' => array (
        'file'        => '/grade/export/banner/lib.php',
        'function'  => 'process_grade',    // argument to call_user_func(), could be an array
        'timing'    => 'cron'
    );
);

These are parsed during install / upgrade and stored in a simple database table.

Then, when a grade_added event happens, all the registered functions for that event will be called something like this (but with more error handling):

         include_once($CFG->dirroot.$events['grade_added']['file'];
         call_user_func($events['grade_added']['function'], $eventdata);

All plugins in Moodle have access to this and can this easily “hook in” to 'grade_added' events (and of course any other events).


Standards for naming events

All event names should follow a consistent naming pattern, such as ...

Database structure

etc