Moodle课程报名

Moodle course enrollment

这是注册用户加入课程的正确方法吗?

$context = get_context_instance(CONTEXT_COURSE, $courseid);     
$roleid = 9;
is_enrolled($context, $USER->id, $roleid);

enrol_try_internal_enrol($courseid, $USER->id, $roleid );

当我执行时,一次说 5 门课程,它有时会在 5 门课程中注册 3 门课程,并且还会注册其他类别的课程。

enrol_try_internal_enrol 会做你想做的,但它只使用 manual 注册方法。要使用不同的注册方法或进行更多控制:

// Depends on the enrolment method you want to use.
// This uses the standard manual enrolment.
if (!enrol_is_enabled('manual')) {
    // Manual enrolment not enabled at the site level.
    debugging('Manual enrolment is not enabled', DEBUG_DEVELOPER);
    return false;
}

// Get the manual enrol plugin.
if (!$enrolplugin = enrol_get_plugin('manual')) {
    // Might not be installed.
    debugging('Manual enrolment is not available', DEBUG_DEVELOPER);
    return false;
}

// Marker to check if the user was enrolled.
$enrolled = false;

// Look for the manual enrolment instance in this course.
// It might not be enabled at the course level.
$instances = enrol_get_instances($courseid, true);
foreach ($instances as $instance) {
    if ($instance->enrol === 'manual') {
        // Enrol user.
        $enrolplugin->enrol_user($instance, $userid, $roleid);

        $enrolled = true;

        break;
    }
}

if (!$enrolled) {
    debugging('No manual enrol plugin for course id : ' . $courseid, DEBUG_DEVELOPER);
    return false;
}