Moodle | Calling custom function on an event

|
| By Webner

Event driven architecture is inbuilt into Moodle. There are various kinds of events present in moodle like:

1. Course completion
2. Course creation
3. Course deletion
4. Course Module creation
5. Category Creation
etc.

On trigger of an event we can call our custom function of custom block or any custom plugin. Eg we need to send an email to a user when he completes a course. So instead of getting values from completion table we can execute a custom function on course completion event.

Steps:

1. Create file “events.php” in db folder of your plugin.

In this file we define our events that we need to use. It can be one or many:

For Example:

In the code sample below we are using course completion event.

$observers is the array of events that we are using. Eventname is the name of event we want to use. Here we are using Moodle’s inbuilt event. That’s why we are using ‘core’ word here. Callback defines class and function we need to invoke when event triggers :

Events.php
<?php
$observers = array(
 array(
 'eventname' => '\core\event\course_completed',
 'callback' => 'block_abc_observer::store'
 )
)

2. Create folder ‘classes’ and file ‘observer.php’ in the same plugin.

Create a class in observer.php following these naming conventions:

Classname: modtype_modname_observer

Like in our case modtype is ‘block’, modname is ‘abc’ so name of our class is block_abc_observer.

Now, define function with name store, include the file in which function is defined and call your function. Now whenever course gets completed, function store will be called:

Observer.php
<?php
class block_abc_observer {
public static function store(\core\event\base $event) {
     global $DB, $CFG;
     require_once('/../test.php'); //include file that contains custom function
     function _name();      //call custom function
}
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *