首页 > 解决方案 > 通过 Moodle Webservice 获取用户角色

问题描述

我一直在尝试找到一种通过 Moodle 网络服务 API 获取用户角色的方法。

我知道没有端点可以执行此操作,但我无法直接从数据库中检索它们,因为我无权访问客户端的数据库。

还有另一种方法吗?

标签: apiweb-servicesmoodle

解决方案


您可以按照以下方式编写解决方案:

  1. 使用通常的样板代码(version.php 等)创建一个准系统插件,例如本地插件。您可以使用这个其他插件来生成样板代码:https ://moodle.org/plugins/tool_pluginskel
  2. 在 'db/services.php' 中注册一个新的外部函数并在新的或现有的服务中公开它。此处的文档:https ://docs.moodle.org/dev/Adding_a_web_service_to_a_plugin和此处的https://docs.moodle.org/dev/Web_services_API。例如:
$functions = [
    'local_myplugin_get_user_roles' => [
        'classname' => external::class,
        'methodname' => 'get_user_roles',
        'description' => 'gets user roles',
        'type' => 'read',
    ],
];
$services = [
    'My services' => [
        'functions' => [
            'local_myplugin_get_user_roles',
        ],
        'enabled' => 1,
        'restrictedusers' => 0,
        'shortname' => 'local_myplugin',
        'downloadfiles' => 0,
        'uploadfiles' => 0,
    ],
];
  1. 为您的插件(在您之前编码的函数定义中引用)编写一个外部类(例如在 external.php 文件中)。在这个类中为定义的外部函数编写代码(例如,它将获取给定用户 ID 的用户的角色),包括输入和输出处理程序。此处示例:https ://docs.moodle.org/dev/External_functions_API#externallib.php
  2. 在您的外部函数中,要获取给定上下文、用户 ID 等的用户角色列表,您可以使用全局 helper get_user_roles。不要忘记在这个外部函数中编写验证输入参数等所需的代码。
  3. 要将您的新服务和外部功能正确地暴露给外部系统,您需要作为 Moodle 管理员遵循以下设置指南: YOUR_MOODLE_INSTANCE_URL/admin/settings.php?section=webservicesoverview 。最后,您将生成一个用户(Web 服务使用者)和一个令牌,您可以在外部系统中设置它们以使用 Moodle 服务。

快乐编码。


推荐阅读