Moodle Performance 标志

Moodle Performance

社区
SaadRahman01
moodle-performance

Use when optimizing Moodle plugin performance — MUC caching definitions, query optimization, recordsets vs records, ad-hoc and scheduled tasks, lazy loading, OPcache, query log analysis, $PERF, and performance debug toolbar.

概览

发布者SaadRahman01
代码仓库claude-moodle-dev
技能名称moodle-performance
星标数
42
复刻数
7
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 SaadRahman01 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Moodle Performance AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-performance
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-performance .claude/skills/moodle-performance
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Moodle Performance,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Moodle Performance。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Moodle Performance 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Moodle Performance

Overview

Moodle bottlenecks: too many DB queries per request, full-table scans, loading large recordsets into memory, blocking work on the request path. Mitigations: MUC caching, indexes, recordsets, ad-hoc tasks, careful capability checks.

When to Use

  • Page renders slowly / hits per-page query limits
  • N+1 query pattern in loops
  • Memory-blow on large datasets
  • Long-running operations on POST handlers
  • Tuning a custom report or scheduled task

Diagnosis

Performance debug

config.php:

php
$CFG->debug = (E_ALL | E_STRICT);
$CFG->debugdisplay = 1;
$CFG->perfdebug = 15;     // shows query count + timings in footer

Site admin > Development > Debugging > Performance info: enables the footer toolbar (queries, time, memory, MUC hits/misses, sessions reads/writes).

$PERF

php
global $PERF;
$start = microtime(true);
// ... work ...
$PERF->dbqueries++;       // your manual counter
mtrace('Took ' . round(microtime(true) - $start, 3) . 's');

Slow query log

Postgres / MySQL slow-query log — turn on in dev. Moodle prefixes queries with the source class via $CFG->dboptions['debug'].

MUC — Moodle Universal Cache

3 cache modes:

ModeStorageLifetimeUse
MODE_APPLICATIONPersistent (file/Redis/Memcached)Until invalidatedShared computed values
MODE_SESSIONSessionSession lifetimePer-user computed values
MODE_REQUESTPHP requestSingle requestMemoize within request

Define a cache

db/caches.php:

php
<?php
defined('MOODLE_INTERNAL') || die();

$definitions = [
    'active_announcements' => [
        'mode'         => cache_store::MODE_APPLICATION,
        'simplekeys'   => true,
        'simpledata'   => true,
        'ttl'          => 600,
        'invalidationevents' => ['changesin_local_announcements'],
    ],
    'user_dashboard' => [
        'mode'       => cache_store::MODE_SESSION,
        'simplekeys' => true,
    ],
];

Bump version.php after edits.

Use the cache

php
$cache = \cache::make('local_announcements', 'active_announcements');
$value = $cache->get('all');
if ($value === false) {
    $value = $this->compute_announcements();
    $cache->set('all', $value);
}
return $value;

Invalidate

php
\cache_helper::invalidate_by_event('changesin_local_announcements', ['all']);
// or
$cache->delete('all');
$cache->purge();

Trigger invalidation from a settings save or an observer.

simplekeys / simpledata

  • simplekeys: true — keys are alphanum (skips hashing) — faster
  • simpledata: true — values are scalars/arrays of scalars (skips serialization) — much faster

Use both whenever possible.

Static cache (per-request)

php
$cache = \cache::make('local_announcements', 'request_lookup');
// MODE_REQUEST in caches.php — auto-cleared at end of request

DB optimization

Recordsets for large data

php
// BAD — loads everything into memory
$rows = $DB->get_records('huge_table');
foreach ($rows as $r) { /* ... */ }

// GOOD — streams
$rs = $DB->get_recordset('huge_table');
foreach ($rs as $r) { /* ... */ }
$rs->close();      // ALWAYS close

Use get_recordset_sql with LIMIT + offset for batched processing of millions of rows.

Avoid N+1

php
// BAD
foreach ($courses as $c) {
    $teacher = $DB->get_record('user', ['id' => $c->teacherid]);
}

// GOOD — single query
$tids = array_column($courses, 'teacherid');
[$insql, $params] = $DB->get_in_or_equal($tids);
$teachers = $DB->get_records_sql("SELECT * FROM {user} WHERE id $insql", $params);

Indexes

xml
<INDEX NAME="userid-courseid" UNIQUE="false" FIELDS="userid, courseid"/>

Edit via XMLDB editor. Composite index column order matters — most-selective first, leftmost-prefix usable for partial queries.

EXPLAIN your queries

bash
mysql> EXPLAIN SELECT ... ;
postgres=# EXPLAIN ANALYZE SELECT ... ;

Look for:

  • type: ALL (full scan) — needs index
  • Using filesort / Using temporary — sort spilling
  • High rows estimate — selectivity issue

Move work off the request

Ad-hoc task — fire-and-forget

php
// classes/task/send_report.php
namespace local_example\task;
class send_report extends \core\task\adhoc_task {
    public function execute(): void {
        $data = $this->get_custom_data();
        // do work
    }
}

// trigger:
$task = new \local_example\task\send_report();
$task->set_custom_data(['userid' => $user->id, 'reportid' => $r->id]);
$task->set_userid($user->id);     // runs as that user
\core\task\manager::queue_adhoc_task($task);

Tasks run via cron. Long jobs don't block HTTP request.

Scheduled task — recurring

db/tasks.php:

php
$tasks = [[
    'classname' => 'local_example\task\cleanup',
    'blocking'  => 0,
    'minute'    => '0',
    'hour'      => '3',
    'day'       => '*',
    'month'     => '*',
    'dayofweek' => '*',
]];
php
class cleanup extends \core\task\scheduled_task {
    public function get_name(): string {
        return get_string('task:cleanup', 'local_example');
    }
    public function execute(): void {
        // ...
    }
}

Run cron: php admin/cli/cron.php. Production: cron entry every minute.

Locks for non-overlapping execution

php
$locktype = 'local_example_cleanup';
$lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
if (!$lock = $lockfactory->get_lock('main', 5)) {
    return;     // another instance running
}
try {
    // ...
} finally {
    $lock->release();
}

Capability check optimization

has_capability() is expensive at scale. For lists:

php
// BAD — N capability checks
foreach ($users as $u) {
    if (has_capability('mod/quiz:attempt', $context, $u)) { /* ... */ }
}

// GOOD — single batched query
$users = get_users_by_capability($context, 'mod/quiz:attempt', 'u.id, u.firstname, u.lastname');

Output / page

php
$PAGE->set_pagelayout('embedded');     // skips heavy regions when appropriate
$PAGE->add_body_class('skip-some-blocks');

Lazy-load AMD modules:

javascript
// only load when needed
const onClick = async () => {
    const {init} = await import('local_example/heavy');
    init();
};

OPcache + APCu

php.ini:

ini
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0    # production only
opcache.revalidate_freq = 0

Moodle benefits massively from OPcache. With validate_timestamps=0, restart PHP after deploys.

APCu for Moodle config cache: $CFG->localcachedir = '/var/cache/moodle';

Sessions

  • Use Redis sessions in production ($CFG->session_handler_class = '\core\session\redis')
  • File sessions don't scale past one app server
  • Session writes — see "session lock" issues if multiple AJAX requests block on session
php
// release session lock early when only reading
\core\session\manager::write_close();

Frontend

  • Run npx grunt amd — production builds are minified
  • Enable browser caching: $CFG->cachejs = true; $CFG->cachetemplates = true;
  • Theme designer mode ($CFG->themedesignermode) — OFF in production (disables CSS cache)

Common Mistakes

MistakeFix
get_records on huge tableget_recordset + close
N+1 in loopsBatch with get_in_or_equal
Sending email on POSTMove to ad-hoc task
has_capability per rowget_users_by_capability
MUC without simplekeys/simpledataSet both true when possible
MUC MODE_REQUEST for cross-request dataUse MODE_APPLICATION
Long lock without try/finallyRelease in finally block always
Theme designer mode on prodOff — kills CSS caching
validate_timestamps = 1OFF in prod, restart on deploy
Forgetting $rs->close()Recordset leaks — always close
File sessions on multi-app-serverSwitch to Redis/Memcached

Profiling

xhprof / tideways:

php
// quick on-demand profile
$CFG->profilingenabled = true;
$CFG->profilingautostart = false;
// add ?PROFILEME to URL — view in admin/tool/profiling

Per-request: Site admin > Development > Profiling.

References

常见问题

Moodle Performance AI 技能有什么作用?

Use when optimizing Moodle plugin performance — MUC caching definitions, query optimization, recordsets vs records, ad-hoc and scheduled tasks, lazy loading, OPcache, query log analysis, $PERF, and performance debug toolbar.

为什么在 TypingMind 中使用 Moodle Performance?

因为您只需安装一次,就能搭配任何模型使用。Moodle Performance 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Moodle Performance?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-performance。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Moodle Performance?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Moodle Performance 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Moodle Performance 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Moodle Performance AI 技能免费吗?

是的。SaadRahman01 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇