Calling internal functions from a plugin

Calling internal functions from a plugin

by Max hi -
Number of replies: 2

Dear Moodle Development Experts,

I'm trying to figure out if it is possible to call the internal Moodle evalmath functions of class EvalMath (e.g. for evaluating correctness of calculations of grade items) from a plugin.

First, it seems that I need to call them through the calc_formula class from mathslib.php. Can I access functions from this class through the $formula object of a grade_item from a plugin via an API? (I already use a JS plugin with AJAX calls and the data_manipulation api)

Thank you very much in advance!

Kind regards,

Max


Average of ratings: -
In reply to Max hi

Re: Calling internal functions from a plugin

by tim st.clair -
Picture of Plugin developers
Sounds like you want an externallib.php in your plugin that can house the calls to the libraries you want to access internally, then expose these through to javascript using ajax calls. This is basically a web service call, just through ajax.

In your plugin (block/activity/local/etc) you would have a db/services.php to define `$functions` for the class hosting the function call, something iike

$functions = [
  'local_foobar_calcstuff' => [
    'classname' => 'local_foobar_external',
    'methodname' => 'calc_stuff',
    'classpath' => 'local/foobar/externallib.php',
    'description' => 'my name',
    'type' => 'read',
    'capabilities' => 'moodle/course:view',
    'ajax' => true,
    'loginrequired' => true
];

in `local/foobar/externallib.php` you would have its function handlers 

public static function calc_stuff_returns()  {
return new \external_single_structure(
[ ... etc

public static function cal_stuff_parameters() 
return new \external_function_parameters(
[ ... etc

public static function submit_questionnaire_feedback($cmid, $somevalue, ... etc
...
return ['result'=>json_encode($sum)]; // or whatever

(you have to bump the plugin version to register function names in the external functions table)

then from your ajax you might

require(['core/ajax'], function(Ajax) {
var promise;

promise = Ajax.call([{
methodname: 'local_foobar_calcstuff',
args: {
cmid: 5,
somevalue: "2+2",
}
}], true, true, true, 0);

promise[0].then(data => {
return JSON.parse(data.output);
}).then(result => {
// output it somehow
}).fail(console.warn);
});


https://docs.moodle.org/dev/Adding_a_web_service_to_a_plugin will probably explain it better than me



Average of ratings: Useful (1)