Automatic class loading

From MoodleDocs
Jump to: navigation, search

Moodle 2.6


Contents

Class naming

All plugin class names must start with Frankenstyle prefix such as mod_forum_. All core classes must start with core_ prefix.

Class files and locations

PHP files with class definitions must be stored in classes/ subdirectory inside your plugin, for example mod/forum/classes/. Core classes can be stored either in lib/classes/ or in subsystemdir/classes/ subdirectory.

The name of the class file is without the frankenstyle prefix, for example class mod_forum_some_class is stored in file mod/forum/classes/some_class.php, core_frankenstyle class is stored in lib/classes/frankenstyle.php.

Examples

Example of autoloadated class in forum module:

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

Namespaces

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


Example:

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

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

Personal tools
User docs (English)