Note: You are currently viewing documentation for Moodle 1.9. Up-to-date documentation for the latest stable version is available here: Curl refactor proposal.

Curl refactor proposal

From MoodleDocs

I think we need to refactor the use of curl throughout Moodle so that it is much more consistent, more maintainable and less error-prone. Currently, a bug fix to the way curl operates in one area of Moodle (e.g. MNET) will not necessarily be applied to anywhere else curl is used (say filelib or nusoap).

The solution is straightforward - it's a no-brainer to wrap up the required 30-40 lines of curl set up code into the constructor of a curl class, taking the code in filelib as probably the most prevalent usage of curl in Moodle (in terms of bugs most likely to be noticed). This allows us to provide sensible defaults, always use any Moodle proxy settings, put the curl_close call in the destructor, and provide a fallback setoption method to still allow for any tricky corner cases.

Here's a non-Moodly curl class I prepared earlier for the Fez project, inspired in part by the (inadequate at the time) PEAR curl class.

Typical Usage

Wherever Moodle code needs a curl request, we should be able to cover most use cases in just a two lines of code:

$curl = new SimpleCurl($url, $postparams);
$result = $curl->exec();

The $postparams is an associative array of parameter value pairs, and the $url parameter does what it says:

$post = array('surname' => 'Potter', 'firstname' => 'Harry');
$url = 'http://hogwarts.school.nz/webservice/rolecall';

Tricky corner cases can still be covered a setoption() method, which passes it on to a curl_setopt() call:

$curl->setoption(CURLOPT_ENCODING, 'deflate');

Expected Benefits

  • Fixes to Moodle's usage of curl will be fixed Moodle-wide,
  • All usage of curl will use Moodle proxy and other settings,
  • Sensible defaults can apply Moodle-wide,
  • Flexibility for corner cases is retained,
  • Moodle curl code becomes much more readable and maintainable, and
  • Encapsulation reduces usage in most cases to two lines of code.

Let me know any thoughts/comments improvements in the talk page, by editing this directly, by email or in the Moodle Dev chat. Cheers!

Jonathan Harker 00:19, 29 July 2009 (UTC)

Update:

It might be feasible to use something like http://pear.php.net/package/HTTP_Request2 which has pluggable backends, one of which already wraps curl. I haven't studied it in detail yet though.