Search code examples
phpajaxweb-servicesmoodlemoodle-api

Should I use a web service if I am not performing CRUD operations on DB?


I am writing a simple live search block plugin. I access resources of an external website via API and display the results that matches what the user is searching as they type. I am planning to write a web service that will do this. I will pass the user input as one of the args in the ajax.call and then my web service function will return the suggested result. I am wondering if using a web service is necessary since I am not retrieving or returning any data from the Moodle database and I don't want to store the suggestions but only display them.

For now I am using XMLHttpRequest to call an internal php file in my plugin that connects via api and returns the result, but I would like to know if there is a recommended way to do this.

//the ajax call
ajax.call([{
    methodname: 'block_xxxx_loadpages',
    args: {userinput: userinput},}])


// the webservice function

class block_xxxx_external extends external_api {

  //parameters
  public static function loadpages() {
    return new external_function_parameters (
      array('userinput' => new external_value(PARAM_TEXT, 'the user input'))
    );
  }

  //the function
  public static function loadpages($userinput = 'userinput') {

    //parameter validation
    $params = self::validate_parameters(self::hello_world_parameters(),
    array('userinput' => $userinput));

    //connect to api and return the result page matching the userinput

    return $result;

  }

  public static function loadpages_returns() {
    return new external_value(PARM_TEXT, 'the result')
  }

}

Solution

  • It is not mandatory to have web service for every ajax call in moodle unless you handle the exceptions and capabilities well. You can use regular XML HttpRequest to get the data.