Automatic class loading

Jump to: navigation, search

Moodle 2.6

This document describes how to use the functionality of the automatic classloader provided by Moodle.

Class naming

To be discoverable by the Moodle automatic classloader, classes must adhere to the following class naming rules:

  • Frankenstyle Prefixes
    • Core classes must start with the prefix core_.
    • Plugin class names must start with names such as plugintype_pluginname_. For example: mod_forum_ (in the example of /mod/forum)
  • One class file for each class
  • Class file names must be class name without Frankenstyle prefix
    • e.g. Class mod_forum_some_class is stored in file mod/forum/classes/some_class.php
    • e.g. Class core_frankenstyle class is stored in lib/classes/frankenstyle.php

Class files and locations

The Moodle automatic classloader looks for classes only in specific locations (all caps represents a symbolic name, replace it with a real location)

  • Core classes
    • /lib/classes/ and its subdirectories
    • SUBSYSTEMDIR/classes/ and its subdirectories
      • The list of subsystems and their respective directories can be found in code (/lib/components.json under subsystems)
  • Plugin classes
    • /PLUGIN/DIR/classes and its subdirectories

Code Examples

Example of autoloaded class in forum module:

// file mod/forum/classes/some_class.php
class mod_forum_some_class {
// file mod/forum/lib.php
// no require_once() necessary here
$instance = new mod_forum_some_class();
// in any file
if (class_exists('mod_forum_some_class')) {
  // do something


PHP namespaces are designed to improve code organisation in your projects. Directory structure in classes/ is matching the namespace structure.


namespace core\event;
// file lib/classes/event/base.php
class base {
namespace mod_forum\event;
// file mod/forum/classes/event/post_read.php
class post_read extends \core\event\base {
// in any file
\mod_forum\event\post_read::create($post->id, ...)->trigger();

Note there are restrictions on valid choices for the first and second level namespaces in Moodle - see Coding_style#Namespaces for more info.

Backwards compatibility

There are no know issues that could cause backwards incompatibility, however it is strongly recommended to use the classes subdirectory only for classes that are included automatically.

Performance and developer mode

Class autoloading improves performance and reduces memory footprint. Location of all classes is automatically stored in class map cache, the cache is updated automatically before upgrade or installation, during cache reset and in developer mode.

There is only one inconvenience - if you add new class or remove it you need to do one of the following:

  • visit yourserver/admin/index.php
  • purge caches
  • or add $CFG->debug = (E_ALL | E_STRICT); to your config.php

Otherwise the new class would not be found.

See also