PsySH provides an interactive REPL for Moodle development, similar to `rails console`. This guide shows how to set it up project-locally with a custom init script, giving you direct access to Moodle’s database and API without polluting the repository.

This is a guide for Moodle developers who want to install and use PsySH on a per-project basis, using an init.php file to load Moodle and helper logic — without polluting the Moodle Git repo.

Installing and Using PsySH REPL for Moodle Development (Project-Scoped)

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

Solin specializes in Moodle development tooling and plugin development.

Contact us