External functions API
From MoodleDocs
Overview
The External functions API allows you to create fully parameterised methods that can be accessed by external programs (such as Web services).
externallib.php
- This file is located at the root of your plugin.
- This file is composed by a class that contains the external functions and their descriptions.
<?php
/**
* PLUGIN external file
*
* @package local_PLUGIN
* @copyright 2011 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir . "/externallib.php");
class local_PLUGIN_external extends external_api {
/**
* Returns description of method parameters
* @return external_function_parameters
*/
public static function FUNCTIONNAME_parameters() {
return new external_function_parameters(
array('PARAM1' => new external_value(PARAM_TYPE, 'human description of PARAM1'))
);
}
/**
* The function itself
* @return string welcome message
*/
public static function FUNCTIONNAME($PARAM1) {
//Parameter validation
//REQUIRED
$params = self::validate_parameters(self::FUNCTIONNAME_parameters(),
array('PARAM1' => $PARAM1));
//Context validation
//OPTIONAL but in most web service it should present
$context = get_context_instance(CONTEXT_TYPE, $instanceid);
self::validate_context($context);
//Capability checking
//OPTIONAL but in most web service it should present
if (!has_capability('moodle/xxx:yyy', $context)) {
throw new moodle_exception('cannotrunfunctionname');
}
return $returnedvalue;
}
/**
* Returns description of method result value
* @return external_description
*/
public static function FUNCTIONNAME_returns() {
return new external_value(PARAM_TYPE, 'human description of the returned value');
}
}
Example
You will find an example of an external.php file in the web service template plugin. This plugin contains a web service hello_world function. To make testing easy for you, the plugin is distributed with a test client in the folder /client.