diff --git a/.upgradenotes/MDL-83892-2025022410503826.yml b/.upgradenotes/MDL-83892-2025022410503826.yml new file mode 100644 index 00000000000..ea2e56f357a --- /dev/null +++ b/.upgradenotes/MDL-83892-2025022410503826.yml @@ -0,0 +1,9 @@ +issueNumber: MDL-83892 +notes: + core: + - message: >- + A new method get_instance_record has been added to cm_info object so + core can get the activity table record without using the $DB object + every time. Also, the method caches de result so getting more than once + per execution is much faster. + type: improved diff --git a/lib/modinfolib.php b/lib/modinfolib.php index b591186bc46..ad504357356 100644 --- a/lib/modinfolib.php +++ b/lib/modinfolib.php @@ -1481,6 +1481,12 @@ class cm_info implements IteratorAggregate { */ private $iconcomponent; + /** + * The instance record form the module table + * @var stdClass + */ + private $instancerecord; + /** * Name of module e.g. 'forum' (this is the same name as the module's main database * table) - from cached data in modinfo field @@ -2216,6 +2222,25 @@ class cm_info implements IteratorAggregate { return $cmrecord; } + /** + * Return the activity database table record. + * + * The instance record will be cached after the first call. + * + * @return stdClass + */ + public function get_instance_record() { + global $DB; + if (!isset($this->instancerecord)) { + $this->instancerecord = $DB->get_record( + table: $this->modname, + conditions: ['id' => $this->instance], + strictness: MUST_EXIST, + ); + } + return $this->instancerecord; + } + /** * Returns the section delegated by this module, if any. * diff --git a/lib/tests/modinfolib_test.php b/lib/tests/modinfolib_test.php index 09b722703f3..39ae418d1b8 100644 --- a/lib/tests/modinfolib_test.php +++ b/lib/tests/modinfolib_test.php @@ -2240,4 +2240,34 @@ final class modinfolib_test extends advanced_testcase { $cms = $sectioninfo->get_sequence_cm_infos(); $this->assertCount(0, $cms); } + + /** + * Test for cm_info::get_instance_record + * + * @covers \cm_info::get_instance_record + * @return void + */ + public function test_section_get_instance_record(): void { + global $DB; + + $this->resetAfterTest(); + + $course = $this->getDataGenerator()->create_course(['numsections' => 2]); + $activity = $this->getDataGenerator()->create_module('page', ['course' => $course], ['section' => 0]); + + $modinfo = get_fast_modinfo($course->id); + $cminfo = $modinfo->get_cm($activity->cmid); + + $instancerecord = $DB->get_record('page', ['id' => $activity->id]); + + $instance = $cminfo->get_instance_record(); + $this->assertEquals($instancerecord, $instance); + + // The instance record should be cached. + $DB->delete_records('page', ['id' => $activity->id]); + + $instance2 = $cminfo->get_instance_record(); + $this->assertEquals($instancerecord, $instance); + $this->assertEquals($instance, $instance2); + } }