get_record_snapshot in an event observer

get_record_snapshot in an event observer

by tim st.clair -
Number of replies: 4
Picture of Plugin developers

I'm listening to the \core\event\course_completed event and performing an action (a curl call). While looking at the somewhat vapid documentation [... which I could fix] and reading through code in Moodle and its plugins, I'm finding that some event consumers just look directly at properties of the $event object passed in

$courseid = $event->courseid;
$userid = $event->relateduserid;

whilst other plugins use

$eventdata = $event->get_record_snapshot('course_completions, $event->objectid);
$userid = $eventdata->relateduserid;

I'm thinking that the latter is probably more "correct", but I wanted to ask.

Average of ratings: -
In reply to tim st.clair

Re: get_record_snapshot in an event observer

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

The two are for different purposes.

$event->courseid - this is the id data that is essential to the meaning of the event

$event->get_record_snapshot(...) - this gets an extra 'helper' data object - (potentially) saving the use of a database query to retrieve the data object from the database. This data is not stored in the logs, nor is it available to reports, but is there for event handlers to use.

See https://docs.moodle.org/dev/Event_2#Record_caching for more details.


In reply to Davo Smith

Re: get_record_snapshot in an event observer

by tim st.clair -
Picture of Plugin developers

Ok, after re-reading the events2 documentation about 10 times, I think I get it; it's effectively data that's available for the lifetime of the event only that's grabbed during the setup of the event in order to possibly avoid re-looking it up inside each consumer of the event, right?

In reply to tim st.clair

Re: get_record_snapshot in an event observer

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Yes (but note also it is a snapshot of the data at the point when the event fires - any subsequent actions, such as those taken by other event handlers, will not be reflected in the snapshot; the documentation also states that is falls-back on a database query, if the data was not stored when the event was fired).


In reply to tim st.clair

Re: get_record_snapshot in an event observer

by Michael Aherne -
Picture of Core developers Picture of Peer reviewers Picture of Plugin developers

It's also important for "delete" type events, as it provides the record that was deleted which obviously can't be looked up any more!