Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Hooks spec: Difference between revisions

From MoodleDocs
 
(22 intermediate revisions by 7 users not shown)
Line 1: Line 1:
= Moodle hooks/features (Proposal) =
= Moodle hooks/features (Abandoned) =


== Summary ==
{{Note|This proposal was worked on for several years but no consensus was reached. A decision was made by the integrators to abandon this project as it has consumed too much of the development communities time and resources. The text on this page is kept for historical reasons only. See the comments on MDL-44078 for the full discussion.|gotcha}}


Allow plugins to substitute or extend some core code where change is not big enough to create a new plugin type but we want to allow plugins interactions. Create management UI where admin can see the list of all available hooks/features definitions and available implementations, enable/prioritise implementations.
If you are looking for the existing callback based API please see:
 
https://docs.moodle.org/dev/Callbacks
 
 
 
The full discussion is available on MDL-44078 and in forum: https://moodle.org/mod/forum/discuss.php?d=254508 and https://moodle.org/mod/forum/discuss.php?d=327349 but this issue is dead, please lets not keep discussing it.
 
==Terms used==
 
Terminology in the discussion around this feature has often been confusing because of the ways that other systems have used them (eg Drupal).
 
As a guide - the following terms are equivalent and any other interpretation is not allowed:
 
* '''hook''' === hook point === trigger === caller
* '''callback''' === listener === executor
 
== Goals ==
 
# Create a consistent/simple/performant/secure way to create extension points where all plugins can run code (never specific plugin types) and modify data (no restrictions - not tied specifically to events)
# Create a consistent/simple/performant/secure way to call code from another specific plugin
# Allow implementations in an autoloaded class
# Allow implementations in lib.php (only for legacy)
# Allow testing hook implementations even if no plugin in core currently implements a callback
# Enforce organisation and categorisation of all "callers" and "executors" in a plugin/subsystem/core
 
=== Disregarded Goals ===
This section is only kept to show the history of this issue - these goals were initially listed, but since then nobody requested and they seem like a bad idea (overly complex - no use case).
# Provide an admin UI to control the executed plugins for each hook (order and enable/disable)
# Dropping in a hook implementation from some other large framework/web app that does not suit Moodle
# Blowing this feature up into some full controller for business logic / dependency injection / bloat


== Current solutions ==
== Current solutions ==


* Renderers. These can be used to override a lot of standard Moodle behaviour, particularly on the view side. They can be abused to override even more.
* Defining functions in /plugindir/lib.php with the name <pluginname>_<hookname> and querying all plugins if somebody implements function and/or list of plugins implementing it. *This is the current implementation of hooks.* Disadvantage: functions must be defined in lib.php therefore they are always included even when function is not there (performance loss); no UI to configure if only one plugin can implement feature; difficult for developers because they don't know if they can or how they can implement a hook (no separate place for documentation).


* Events system. The core notifies whoever wants to listen to it about something that happens. Disadvantage: one-way communication, no feedback. Advantage: plugins cannot break important core functionality.
* Events system. The core notifies whoever wants to listen to it about something that happens. Disadvantage: one-way communication, no feedback. Advantage: plugins cannot break important core functionality.


* Defining functions in /plugindir/lib.php with the name <pluginname>_<hookname> and querying all plugins if somebody implements function and/or list of plugins implementing it. Disadvantage: functions must be defined in lib.php therefore they are always included (performance loss); no UI to configure if only one plugin can implement feature; difficult for developers because they don't know if they can or how they can implement a hook.
* $CFG variables. These are fine if it makes sense to have a setting to choose different implementations of a feature (e.g. lock factories).


* $CFG variables. Disadvantage: they should be used for settings and not for including the 3rd party code
* Creating a new plugin type. Disadvantage: very long process, involves lots of documentation, creating lots of strings and UI, may be available in major releases only. Also not applicable for minor features. Forcing a "feature" to be split amongst many plugins.


* Creating a new plugin type. Disadvantage: very long process, involves lots of documentation, creating lots of strings and UI, may be available in major releases only. Also not applicable for minor features.
* Renderers. These can be used to override a lot of standard Moodle behaviour, particularly on the view side. Only can be overridden by themes


== Implementation ==
== Implementation ==


Very similar to [[Events API]] but with much less restrictions and more flexibility
* Hook definition is a class stored in /classes/hook/ folder (of core component or plugin). They have a function execute() that calls all registered callbacks and passes the actual instance of the hook definition class to them. Some hooks may be called on one component/plugin at a time only.


* Hook definition is a class stored in /classes/hook/ folder (of core component or plugin). They have a function execute() that calls all registered callbacks and passes the actual instance of the hook definition class to them.  
* Hooks to be executed must be registered in /db/hooks.php so it is possible to determine all the hooks called by a plugin/subsystem.


* Plugins that want to register hook callbacks do so in /db/hook.php the same way events do
* Plugins that want to register hook executions (callbacks) do so in /db/hooks.php


* Hook manager, very similar to event manager, is responsible for caching of the list of existing hooks and their callbacks. It also has an interface with list of all hooks and callbacks.
* Hook manager, is responsible for caching of the list of existing hooks and their callbacks. It also has an interface with list of all hooks and callbacks.
 
* Hook callbacks are called recursively in a way similar to legacy events.


=== Example ===
=== Example ===
Line 38: Line 66:
abstract class base {
abstract class base {
     private $isexecuting = false;
     private $isexecuting = false;
     public function execute() {
     public function execute($component = null) {
         if ($this->isexecuting) {
         if ($this->isexecuting) {
             throw new \moodle_exception('Already executing');
             throw new \moodle_exception('Already executing');
         }
         }
         $this->isexecuting = true;
         $this->isexecuting = true;
         \core\hook\manager::dispatch($this);
         \core\hook\manager::dispatch($this, $component);
         $this->isexecuting = false;
         $this->isexecuting = false;
         return $this;
         return $this;
Line 50: Line 78:
</pre>
</pre>


1. '''/course/classes/hook/courseresetform.php'''
1. '''/lib/classes/hook/courseresetform.php'''


<pre>
<pre>
namespace core_course\hook;
namespace core\hook;
public class courseresetform extends \core\hook\base {
public class courseresetform extends \core\hook\base {
     private $mform;
     private $mform;
     public function __get($name) {
     public function get_mform() {
         if ($name === 'mform') {
         return $this->mform;
            // Mform is a read-only property.
            return $this->mform;
        }
     }
     }
     public static function create($mform) {
     public static function create($mform) {
Line 71: Line 96:


2. '''/course/reset_form.php''', function course_reset_form::definition()
2. '''/course/reset_form.php''', function course_reset_form::definition()
at the moment this function looks for function xxx_reset_course_form_definition() in all mod plugins and call this function passing $mform. It will continue doing so for backward compatibility but also it can call:
at the moment this function looks for function xxx_reset_course_form_definition() in all mod plugins and call this function passing $mform. We can have a legacy hook execution that does this for backward compatibility but it will just call:
<pre>
\core\hook\courseresetform::create($mform)->execute();
</pre>
The hook also must be listed in db/hooks.php
<pre>
<pre>
\core_course\hook\courseresetform::create($mform)->execute();
// Hooks that exist in Moodle core.
$hooks = array(
    '\core\hook\courseresetform',          // Allows components/plugins to extend the course reset form.
);
</pre>
</pre>


 
3. Now any plugin type and not only module but also blocks (existing issue MDL-24359) can register their callbacks in '''/blocks/myblock/db/hooks.php'''.
3. Now any plugin type and not only module but also blocks (existing issue MDL-24359) can register their callbacks in '''/blocks/myblock/db/hook.php'''.
<pre>
<pre>
$callbacks = array(
$callbacks = array(
     array(
     array(
         'hookname'    => '\core_course\hook\courseresetform',
         'hookname'    => '\core\hook\courseresetform',
         'callback'    => array('block_myblock_hook_callbacks', 'reset'),
         'callback'    => array('block_myblock_hook_callbacks', 'courseresetform'),
         //'invludefile' => '/optional/file/path.php',
         //'includefile' => '/optional/file/path.php',
     ),
     ),
);
);
Line 92: Line 123:
<pre>
<pre>
class block_myblock_hook_callbacks {
class block_myblock_hook_callbacks {
     public static function(\core_course\hook\courseresetform $courseresetformhook) {
     public static function courseresetform(\core\hook\courseresetform $courseresetformhook) {
         $courseresetformhook->mform->addElement('checkbox', 'Reset contents of block Myblock');
         $courseresetformhook->get_mform()->addElement('checkbox', 'Reset contents of block Myblock');
     }
     }
}
}
Line 100: Line 131:
== Use cases ==
== Use cases ==


# Navigation: we want to allow any plugin to put own items anywhere
# Recent activity in course
# Recent activity in course
# Course search: we have quite primitive course search algorithm in core. Some other plugin may implement search with sorting by relevance, analysing tags, going through attached pdf files, etc. Hook implementation returns the list of courses and core goes back to the core/theme renderers to display this list
# Global search: similar to above but result will be list of title+url+abstract
# Global search: similar to above but result will be list of title+url+abstract
# Front page: We have $CFG->customfrontpageinclude for including a file displaying frontpage contents. It could be also hook/feature
# Front page: We have $CFG->customfrontpageinclude for including a file displaying frontpage contents. It could be also hook/feature
Line 107: Line 138:
# Extending licenses list
# Extending licenses list
# Adding fields to the standard forms. This may be a comprehensive feature that includes several functions - adding fields, validation, processing.
# Adding fields to the standard forms. This may be a comprehensive feature that includes several functions - adding fields, validation, processing.
== Comparison with Moodle Events ==
Differences with [[Events API]]:
* events are one way communication (from one to many) - hooks are two way communication (usually many to one)
* event data must not be modified - hook callbacks may alter the hook instance data
* events are triggered after actions - hooks can be executed at any useful stage (pre, post, validation, etc.)
* event structure is fixed - hooks can be arbitrary classes that may extend the base
* database transaction may cause event buffering - hook manager does does not consider transactions
* all events are logged (this is contentious) - hooks are not logged

Latest revision as of 11:22, 6 April 2020

Moodle hooks/features (Abandoned)

Note: This proposal was worked on for several years but no consensus was reached. A decision was made by the integrators to abandon this project as it has consumed too much of the development communities time and resources. The text on this page is kept for historical reasons only. See the comments on MDL-44078 for the full discussion.


If you are looking for the existing callback based API please see:

https://docs.moodle.org/dev/Callbacks


The full discussion is available on MDL-44078 and in forum: https://moodle.org/mod/forum/discuss.php?d=254508 and https://moodle.org/mod/forum/discuss.php?d=327349 but this issue is dead, please lets not keep discussing it.

Terms used

Terminology in the discussion around this feature has often been confusing because of the ways that other systems have used them (eg Drupal).

As a guide - the following terms are equivalent and any other interpretation is not allowed:

  • hook === hook point === trigger === caller
  • callback === listener === executor

Goals

  1. Create a consistent/simple/performant/secure way to create extension points where all plugins can run code (never specific plugin types) and modify data (no restrictions - not tied specifically to events)
  2. Create a consistent/simple/performant/secure way to call code from another specific plugin
  3. Allow implementations in an autoloaded class
  4. Allow implementations in lib.php (only for legacy)
  5. Allow testing hook implementations even if no plugin in core currently implements a callback
  6. Enforce organisation and categorisation of all "callers" and "executors" in a plugin/subsystem/core

Disregarded Goals

This section is only kept to show the history of this issue - these goals were initially listed, but since then nobody requested and they seem like a bad idea (overly complex - no use case).

  1. Provide an admin UI to control the executed plugins for each hook (order and enable/disable)
  2. Dropping in a hook implementation from some other large framework/web app that does not suit Moodle
  3. Blowing this feature up into some full controller for business logic / dependency injection / bloat

Current solutions

  • Defining functions in /plugindir/lib.php with the name <pluginname>_<hookname> and querying all plugins if somebody implements function and/or list of plugins implementing it. *This is the current implementation of hooks.* Disadvantage: functions must be defined in lib.php therefore they are always included even when function is not there (performance loss); no UI to configure if only one plugin can implement feature; difficult for developers because they don't know if they can or how they can implement a hook (no separate place for documentation).
  • Events system. The core notifies whoever wants to listen to it about something that happens. Disadvantage: one-way communication, no feedback. Advantage: plugins cannot break important core functionality.
  • $CFG variables. These are fine if it makes sense to have a setting to choose different implementations of a feature (e.g. lock factories).
  • Creating a new plugin type. Disadvantage: very long process, involves lots of documentation, creating lots of strings and UI, may be available in major releases only. Also not applicable for minor features. Forcing a "feature" to be split amongst many plugins.
  • Renderers. These can be used to override a lot of standard Moodle behaviour, particularly on the view side. Only can be overridden by themes

Implementation

  • Hook definition is a class stored in /classes/hook/ folder (of core component or plugin). They have a function execute() that calls all registered callbacks and passes the actual instance of the hook definition class to them. Some hooks may be called on one component/plugin at a time only.
  • Hooks to be executed must be registered in /db/hooks.php so it is possible to determine all the hooks called by a plugin/subsystem.
  • Plugins that want to register hook executions (callbacks) do so in /db/hooks.php
  • Hook manager, is responsible for caching of the list of existing hooks and their callbacks. It also has an interface with list of all hooks and callbacks.

Example

Typical example is a hook that allows plugins to add fields to the existing form. Note that actual hook classes may be much more complicated, with lots of methods that can be called from callbacks and also with properties/methods that can be called by the component who executed the hook to access the collected data from plugins.

0. Base class does almost nothing, it's just a suggestion for implementation, methods are not final (unlike events) /lib/classes/hook/base.php

namespace core\hook;
abstract class base {
    private $isexecuting = false;
    public function execute($component = null) {
        if ($this->isexecuting) {
            throw new \moodle_exception('Already executing');
        }
        $this->isexecuting = true;
        \core\hook\manager::dispatch($this, $component);
        $this->isexecuting = false;
        return $this;
    }
}

1. /lib/classes/hook/courseresetform.php

namespace core\hook;
public class courseresetform extends \core\hook\base {
    private $mform;
    public function get_mform() {
        return $this->mform;
    }
    public static function create($mform) {
        $hook = new self();
        $hook->mform = $mform;
        return $hook;
    }
}

2. /course/reset_form.php, function course_reset_form::definition() at the moment this function looks for function xxx_reset_course_form_definition() in all mod plugins and call this function passing $mform. We can have a legacy hook execution that does this for backward compatibility but it will just call:

\core\hook\courseresetform::create($mform)->execute();

The hook also must be listed in db/hooks.php

// Hooks that exist in Moodle core.
$hooks = array(
    '\core\hook\courseresetform',           // Allows components/plugins to extend the course reset form.
);

3. Now any plugin type and not only module but also blocks (existing issue MDL-24359) can register their callbacks in /blocks/myblock/db/hooks.php.

$callbacks = array(
    array(
        'hookname'    => '\core\hook\courseresetform',
        'callback'    => array('block_myblock_hook_callbacks', 'courseresetform'),
        //'includefile' => '/optional/file/path.php',
    ),
);


4. Actual callback implementation from /blocks/myblock/classes/hook_callbacks.php:

class block_myblock_hook_callbacks {
    public static function courseresetform(\core\hook\courseresetform $courseresetformhook) {
        $courseresetformhook->get_mform()->addElement('checkbox', 'Reset contents of block Myblock');
    }
}

Use cases

  1. Navigation: we want to allow any plugin to put own items anywhere
  2. Recent activity in course
  3. Global search: similar to above but result will be list of title+url+abstract
  4. Front page: We have $CFG->customfrontpageinclude for including a file displaying frontpage contents. It could be also hook/feature
  5. Extending mimetypes list
  6. Extending licenses list
  7. Adding fields to the standard forms. This may be a comprehensive feature that includes several functions - adding fields, validation, processing.

Comparison with Moodle Events

Differences with Events API:

  • events are one way communication (from one to many) - hooks are two way communication (usually many to one)
  • event data must not be modified - hook callbacks may alter the hook instance data
  • events are triggered after actions - hooks can be executed at any useful stage (pre, post, validation, etc.)
  • event structure is fixed - hooks can be arbitrary classes that may extend the base
  • database transaction may cause event buffering - hook manager does does not consider transactions
  • all events are logged (this is contentious) - hooks are not logged