Module 2: PHP for Moodle Developers

Moodle Coding Style, Global Objects, and Helper Functions

1. Moodle Coding Style

Moodle has a strict coding style (based on PSR-12 but with specifics). Key rules:

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.