
本文详解如何在 moodle 自定义区块(如页脚)中安全、准确地获取并展示当前用户的角色名称,涵盖数据库查询优化、moodle 原生 api 使用及常见错误规避。
本文详解如何在 moodle 自定义区块(如页脚)中安全、准确地获取并展示当前用户的角色名称,涵盖数据库查询优化、moodle 原生 api 使用及常见错误规避。
在 Moodle 开发中,直接通过 role_assignments 表查询用户角色看似直观,但存在两个关键问题:一是该表仅存储 roleid(整数),不包含角色名称;二是代码中误用了未定义变量 $user->id(应为 $USER->id)。更严重的是,role_assignments 表记录的是「角色分配」,其作用范围依赖于上下文(context),若不指定 context,可能返回空结果或权限错误。
✅ 推荐方案:使用 Moodle 内置函数 get_user_roles()
该函数自动处理上下文、权限和缓存,返回结构化角色对象数组,包含 name、shortname、id 等字段,语义清晰且符合 Moodle 最佳实践。
以下是修正后的 get_content() 方法完整实现:
function get_content() {
global $USER, $DB;
if ($this->content !== null) {
return $this->content;
}
$this->content = new stdClass();
$this->content->text = ''; // 可选:主内容区域留空或添加说明
$this->content->footer = ''; // 初始化 footer 字符串
// ✅ 正确方式:获取当前用户在系统级上下文中的所有角色
try {
$roles = get_user_roles(context_system::instance(), $USER->id);
if (!empty($roles)) {
$roleNames = [];
foreach ($roles as $role) {
$roleNames[] = s($role->name); // s() 用于安全转义 HTML 特殊字符
}
$this->content->footer = '<div class="block-role-footer">' .
'Roles: ' . implode(', ', $roleNames) .
'</div>';
} else {
$this->content->footer = '<div class="block-role-footer">No roles assigned</div>';
}
} catch (Exception $e) {
$this->content->footer = '<div class="block-role-footer error">Error loading roles</div>';
debugging('Failed to load user roles: ' . $e->getMessage(), DEBUG_DEVELOPER);
}
return $this->content;
}? 关键注意事项:
-
上下文选择要合理:
context_system::instance()获取系统级角色(如管理员、访客),若需课程级角色,请改用context_course::instance($courseid); -
始终校验
$USER:确保用户已登录(可加require_login()或检查$USER->id); -
HTML 安全性:使用
s()函数对角色名转义,防止 XSS; -
性能友好:
get_user_roles()已内置缓存,无需手动优化; -
错误处理不可少:生产环境务必包裹
try/catch并记录调试信息。
? 进阶提示:如需显示角色图标或链接到角色管理页,可结合 $OUTPUT->pix_icon() 和 new moodle_url('/admin/roles/define.php', ['roleid' => $role->id]) 实现。
通过以上方式,你不仅能正确显示角色名称,还能确保代码健壮、安全且与 Moodle 架构深度集成。

















