1. Moodle Coding Style
Moodle has a strict coding style (based on PSR-12 but with specifics). Key rules:
- Indentation: 4 spaces (no tabs).
- Line Length: 132 characters max.
- Naming:
- Classes:
snake_case(e.g.,local_myplugin_observer). - Methods:
camelCase. - Variables:
snake_case(no camelCase for vars). - Constants:
UPPER_CASE.
- Classes:
- Boilerplate: Every file must start with
defined('MOODLE_INTERNAL') || die();unless it's an entry point (like index.php).
2. Global Objects
Moodle relies heavily on global objects. You must declare them with global $VAR; inside functions.
| Variable | Description |
|---|---|
$DB |
The Database Manager (DML). Used for all database queries. |
$CFG |
Configuration object. Holds site settings (e.g., $CFG->wwwroot, $CFG->dataroot). |
$USER |
The current logged-in user object. |
$PAGE |
The Page setup object. Controls title, layout, and requirements. |
$OUTPUT |
The Output renderer. Used to generate HTML (headers, footers, buttons). |
$SESSION |
The custom Moodle session object. |
3. Essential Helper Functions
Moodle provides thousands of helper functions in lib/moodlelib.php and lib/weblib.php.
Input Handling
// Get parameters from GET/POST
$id = required_param('id', PARAM_INT); // Dies if missing
$action = optional_param('action', 'view', PARAM_ALPHA); // Default 'view'
// PARAM Types are crucial for security
// PARAM_INT, PARAM_TEXT, PARAM_NOTAGS, PARAM_EMAIL, PARAM_BOOL
Output Handling
// String formatting
echo s($user_input); // Escape HTML (like htmlspecialchars)
echo format_string($name); // Format short text (titles)
echo format_text($content); // Format long text (HTML editor content)
// Language strings
echo get_string('pluginname', 'local_myplugin');
echo get_string('welcome', 'local_myplugin', $a_object); // With variables
Debugging
// Print object to screen (only if debug mode is on)
debugging('Something went wrong', DEBUG_DEVELOPER);
// Dump variable (like var_dump but formatted)
print_object($some_array);
4. Modern PHP in Moodle
While Moodle has a lot of legacy code, modern versions (4.1+) support PHP 8.1 features.
- Namespaces: All new plugins should use namespaces.
local/myplugin/classes/observer.php->namespace local_myplugin; class observer {} - Type Hinting: Use strict types in your new classes.
- Autoloading: Classes in
classes/folder are automatically loaded.