Overview

This guide helps Moodle developers:

  • Set up an interactive REPL (like rails console or irb) using PsySH

  • Run it within a Moodle context (with $CFG, $DB, $USER, etc.)

  • Keep all files outside the Git-tracked Moodle directory

  • Ensure correct PHP version is used per project

1. Requirements

  • PHP CLI (matching your project version, e.g. php7.4)

  • Composer (any global version)

  • Local Moodle install (e.g. in ~/php/icm/public_html/)

2. Install PsySH per project

Create a tools/ directory next to your Moodle root:

cd ~/php/icm
mkdir tools && cd tools

php7.4 /usr/bin/composer require psy/psysh:^0.11

This installs a project-local version of PsySH compatible with PHP 7.4. (Assumption: your webroot is something like ~/php/icm/public_html)

3. Create init.php to bootstrap Moodle and helpers

Inside ~/php/icm/tools/init.php, add:

<?php
// Load Moodle
define('CLI_SCRIPT', true);
require(__DIR__ . '/../public_html/config.php');
// Simulate a logged-in admin user
$USER = get_admin();
// Setup typical Moodle page context
$PAGE = new moodle_page();
$PAGE->set_context(context_system::instance(;
$PAGE->set_url('/');
$PAGE->set_pagelayout('admin');
$COURSE = get_site();
$SITE = $COURSE;
// Optional helpers
function uname(int $id): string {

global $DB;

$user = $DB->get_record(‘user’, [‘id’ => $id], ‘*’, MUST_EXIST);

return fullname($user);
}
echo "[Moodle REPL ready -- user={$USER->username}]\n";

This gives you access to the full Moodle environment in the REPL.

4. Create a launch script: moodlerepl

Inside ~/php/icm/tools/, create:

touch moodlerepl

chmod +x moodlerepl

With the contents:

#!/usr/bin/env bash
DIR="$(cd "$(dirname "$0")" && pwd)"
PHPBIN="php7.4" # Change if needed

“$PHPBIN” “$DIR/vendor/bin/psysh” “$DIR/init.php”

Now you can just run:

./moodlerepl

5. Example REPL session

$ ./moodlerepl

[Moodle REPL ready — user=admin]

Psy Shell v0.12.7 (PHP 7.4.33 — cli)

>>> $DB->get_record(‘user’, [‘id’ => 2]);

>>> uname(2);

6. Keep everything out of Git

Add this to your .gitignore if needed:

tools/

Or selectively ignore:

tools/vendor/

tools/init.php

tools/moodlerepl

Notes

Topic Detail
PHP version Always run with the project’s PHP version (e.g. php7.4)
Moodle Git repo Never modified — tools/ is outside the repo
Composer usage Only inside tools/ folder — not inside Moodle root
Config files Global PsySH config is not needed — all logic is in init.php

Summary

Step What to do
1. mkdir tools && cd tools
2. php7.4 /usr/bin/composer require psy/psysh:^0.11
3. Create init.php with Moodle context
4. Create moodlerepl script
5. Run ./moodlerepl to enter Moodle REPL

Solin helps developers work faster in Moodle and Totara codebases with practical tooling, debugging workflows, and engineering support. Need help? Contact us.

Contact us